Skip to content

Instantly share code, notes, and snippets.

@mgd020
Last active June 30, 2016 00:37
Show Gist options
  • Save mgd020/9e4d906b243bf1faa4b8a48af2cb2534 to your computer and use it in GitHub Desktop.
Save mgd020/9e4d906b243bf1faa4b8a48af2cb2534 to your computer and use it in GitHub Desktop.
javascript dom html template rendering
/*
renderTemplate(template_id, context) -> string
Renders a template declared in the DOM with a given context.
Template tags:
<% ... %>: code
<%= ... %>: added to output
Example:
<div id="example"></div>
<script type="text/x-template", id="example-template">
<ul>
<% for (var i = 0; i < count; ++i) { %>
<li><%= i %></li>
<% } %>
</ul>
</script>
<script>
document.getElementById('example').innerHTML = renderTemplate('example-template', {count: 4})
</script>
*/
window['renderTemplate'] = (function () {
var cache = {};
function compileTemplate(template) {
return new Function("_c", 'var _t="";with(_c||{}){_t+=' + JSON.stringify(document.getElementById(template).text).replace(/<%=((.|[\r\n])*?(?=%>))%>/g, '";_t+=$1;_t+="').replace(/<%((.|[\r\n])*?(?=%>))%>/g, '";$1;_t+="') + '}return _t');
}
return function(template, context) {
return (cache[template] || (cache[template] = compileTemplate(template)))(context);
};
})();
/* minified * /
//window.renderTemplate=function(){var b={};return function(a,c){return(b[a]||(b[a]=new Function("_c",'var _t="";with(_c||{}){_t+='+JSON.stringify(document.getElementById(a).text).replace(/<%=((.|[\r\n])*?(?=%>))%>/g,'";_t+=$1;_t+="').replace(/<%((.|[\r\n])*?(?=%>))%>/g,'";$1;_t+="')+"}return _t")))(c)}}();
/* endminified */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment