Skip to content

Instantly share code, notes, and snippets.

@letsgetrandy
Last active April 14, 2018 19:04
Show Gist options
  • Save letsgetrandy/5276677 to your computer and use it in GitHub Desktop.
Save letsgetrandy/5276677 to your computer and use it in GitHub Desktop.
Simple template rendering for Javascript
/* Simple JS template rendering function */
function render(obj, template) {
var re, v;
re = new RegExp("\\[\\[([^\\]]+)\\]\\]");
while (match = re.exec(template)) {
val = obj[match[1]] || '';
template = template.replace(match[0], val);
}
return template;
}
/* sample call to the function */
var template = '<div class="[[classname]]"><span>[[firstname]] [[lastname]]</span><br><span>[[message]]</span></div>';
var obj = { firstname:"Randy", lastname:"Hunt", message:"Hello world!", classname="display" };
document.write(render(obj, template));
/* OUTPUT:
<div class="display">
<span>Randy Hunt</span><br>
<span>Hello World!</span>
</div>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment