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 :
Written by Stefano Azzolini
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Optimization
Authors
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
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#