Search code examples
underscore.jstemplate-engineprecompileunderscore.js-templating

underscore.js precompiled templates using


I want to use precompiled underscore.js templates. I use _.template().source and save result in file. But I don't understand, how to use this templates. Precompiled templates is strings, and I can't cast it to a function. I try to use eval, but it always return parse error.

For example:

<div>
    <% for(var i = 0; i < 5; i++){ %>
        <div><%=i%></div>
    <% } %>
</div>

Standart using:

_.template(tpl).({});

Result:

<div>

    <div>0</div>

    <div>1</div>

    <div>2</div>

    <div>3</div>

    <div>4</div>

</div>

Precompilation:

_.template(tpl).source

Precompiled template:

"function(obj){
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
__p+='<div>\n\t';
 for(var i = 0; i < 5; i++){ 
__p+='\n\t\t<div>'+
((__t=(i))==null?'':__t)+
'</div>\n\t';
 } 
__p+='\n</div>\n';
}
return __p;
}"

Running precompiled template:

var a = eval(tplc);
a({});

Error:

Error
line: 1
message: "Parse error"
sourceId: 139746789246216
__proto__: SyntaxError

Solution

  • I finally found this solution. I can't say that this is elegant solution, but it works. For my example:

    var a = eval('[' + tplc + ']')[0];
    a({});