I\'m planning to use backbone.js and underscore.js for creating website, and I will have lots of underscore templates:
Although both of the above answers work, I found the following to be a much simpler approach.
Places your templates wrapped in script tags into a file (say "templates.html") as follows:
Then the following bit of javascript:
$(document).ready(function() {
url ='http://some.domain/templates.html'
templatesLoadedPromise = $.get(url).then(function(data) {
$('body').append(data)
console.log("Async loading of templates complete");
}).fail(function() {
console.log("ERROR: Could not load base templates");
});
});
Which then let's you select your templates quite simply using the IDs you previously defined. I added the promise
$.when(templatesLoadedPromise).then(function() {
_.template($('#template-1').html(), {'text':'hello world'} )
});
You can then extend this and load multiple files if you want.
As a side note, I've found that any core templates needed for initial page render are better embedded in the HTML (I use tornado modules on the server) but that the above approach works very nicely for any templates needed later (e.g., in my case the templates for a registration widget which I want to use across pages is perfect for this as it'll only be loaded on user interaction and is non-core to the page)