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