Last Updated: February 25, 2016
·
874
· 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="{url}">{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