Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 281
LMnet Avatar asked Sep 12 '13 04:09

LMnet


People also ask

How do you use underscore in JavaScript?

Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

What is underscore template?

The _. template() function is an inbuilt function in the Underscore. js library of JavaScript which is used to compile JavaScript templates into functions that can be evaluated for rendering.


1 Answers

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.

like image 90
mu is too short Avatar answered Sep 19 '22 07:09

mu is too short