Pregunta

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
¿Fue útil?

Solución 2

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({});

Otros consejos

Yes, the source attribute returns the compiled template as a string. You can write that string to a file which defines a JavaScript object literal something like this:

window.JST = { };
JST.some_name = function(obj){ ... };
// The rest of the compiled template functions go here

Then, load that into the browser like any other JavaScript file and you'll end up with a bunch of compiled template functions in JST:

var html = JST.some_name(data);

You can structure the JST definition however you want of course, that just a simple way to illustrate the overall approach.

Remember that whether a string is just some text to be manipulated like any other blob of text (such as writing it to a file) or if it is JavaScript source code depends on who is interpreting the string.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top