Closed Ahrengot closed 11 years ago
Templates are already "cached". If you do:
var template = _.template("string of template code here");
.. that's a cached function that you can reuse without ever having to parse the template string again.
What your example code demonstrates is a way to look up a string out of the DOM -- which isn't the recommended way to store templates in the first place, and is a bit out of scope for Underscore to address.
For what it's worth, the best way to go about this is to precompile templates whenever possible. Doing this on the server is even nicer as it forgoes the overhead in the browser. Using the variable
option is even better as it will remove the with
statement, making your templates several times faster in most cases. Hope you enjoy it like I do. :)
> _.template('<p><%= o.value %></p>', null, {variable: 'o'}).source
"function(o){
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
__p+='<p>'+
((__t=( o.value ))==null?'':__t)+
'</p>';
return __p;
}"
Thanks for clearing this up.
I use the templating engine quite a bit and everybody knows its good practise to cache your jQuery objects if you use them multiple times so I've worked out this little thingy to handle my various templates.
I was wondering if it would make sense to build something like this directly into .js. I imagine the API could look something like `.cacheTemplate('template-id')
and
_.getTemplate('template-id')`.We could set it up similar to the new Tweenlite.selector in GSAP, that checks for an existing selector engine like jQuery or sizzle via
window.$
and falls back todocument.getElementById
if it isn't present.What do you think?