jashkenas / underscore

JavaScript's utility _ belt
https://underscorejs.org
MIT License
27.3k stars 5.53k forks source link

Would something like .cacheTemplate make sense? #958

Closed Ahrengot closed 11 years ago

Ahrengot commented 11 years ago

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 to document.getElementById if it isn't present.

What do you think?

jashkenas commented 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.

braddunbar commented 11 years ago

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;
}"
Ahrengot commented 11 years ago

Thanks for clearing this up.