Django like templates in Javascript
Here's a quick ‘n’ dirty Javascript function I hacked together that provides Django-like template substitution.
function sformat(template, data) { return template.replace(/{{(.*?)}}/g, function(m, n) { return eval('data.'+n); }); }
Used something like this:
sformat("Hello, {{ name }}!", {name:"World"});
Which returns the following string:
Hello, World!
Alas, it doesn't support anything other than substitution. If you need anything more advanced (loops etc), you should investigate Javascript template engines.
http://dojotoolkit.org/book/dojo-book-0-9/part-5-dojox/dojox-dtl
Care to share a usecase?
Fraser, granted, although if the template doesn't come from an external source like an AJAX request, it shouldn't be an issue.
eelco, that's pretty neat.
Dougal, its more elegant than string concatenation, IMHO.
so my code would look like
the less typing, the better :D