Django like templates in Javascript

April 5th, 2009

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.

 
 
© 2008 Will McGugan.

A technoblog blog, design by Will McGugan