I\'m using Backbone and therefore Underscore to render my templates. My templates get rendered in tags and then I use jQuery to grab their html. My
You can build a very simple object that caches the templates for you:
TemplateCache = {
get: function(selector){
if (!this.templates){ this.templates = {}; }
var template = this.templates[selector];
if (!template){
var tmpl = $(selector).html();
template = _.template(tmpl);
this.templates[selector] = template;
}
return template;
}
}
Then in your view, you can call TemplateCache.get
and pass in your template selector.
Backbone.View.extend({
template: "#ItemTemplate",
render: function(){
var template = TemplateCache.get(this.template);
var html = template(this.model.toJSON());
this.$el.html(html);
}
});
The first time you call TemplateCache.get
for a given selector, it will load it from the DOM. Any subsequent calls to get the template will load it from the cached version and prevent the extra DOM access call.
FWIW: I have a much more robust version of the TemplateCache
object in my Backbone.Marionette framework: https://github.com/derickbailey/backbone.marionette