Super simple JS templates with String.prototype.tmpl using Ruby/coffeeScript syntax — Gist

So I wanted to create a super small string interpolator for JavaScript. I really didn't need a full on JS template library. Just a simple helper method that would let me pass an object to a string. You can write a string with "a #{placeholder}" then pass an object to the string with a placeholder key and value..

Example :

"Hi, #{name} you have #{count} credits left".tmpl({ name : "John", count : 10 });

Of course this is somewhat of a contrived example. However, one can see how useful it becomes when you have a long string that you want to reuse with many records.

I borrowed the placeholder syntax from CoffeeScript/Ruby. I am using forEach so some JS engines will not recognize that as a native Array method. Perhaps someone want to commit a more vanilla loop instead!

I'm interested to see other super powerful prototype helpers developers have created. What's your favorite?

-Stephen

Stephen Rhyne

Stephen Rhyne

I am the owner of Rhyne Design (a Web / Mobile Web application development and consulting company located outside the greater Seattle area), CTO at Throwing Boulders, LLC & co-owner of WebPDI.

Married father of 4, Vietnamese food fanboy

Archive

2011 (4)
2010 (10)
2009 (10)
Posterous theme by Cory Watilo