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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With