Last Updated: February 25, 2016
·
1.11K
· 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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside