Last Updated: February 25, 2016
·
964
· lastguest

Fast Templating in JavaScript

function compile_template(template) {
  return new Function('o',
    'o=o||{};return "' +
    template
    .replace(/"/g, '\\"')
    .split('{')
    .join('"+(o.')
    .split('}')
    .join('||"")+"') + '";'
  );
}

Use with a moustache-like syntax "{varname}"

var drawLink = compile_template('<a href="http://coderwall.com/%7Burl%7D">{title}</a>');

Pass template parameters as an object.

drawLink({
    title: 'The Example Website',
    url: 'http://www.example.com/'
})

Results :

<a href="http://www.example.com/">The Example Website</a>

Performances :

http://jsperf.com/simple-javascript-templating