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.

Read full article at “Django posts in ‘It’s All Geek to Me’”

Leave a comment