Need some opinions on the best way to manage templating in Underscore. I'm building a Backbone app and using Underscore to manage the templates. I started off by doing something like this in a 'template.js' file.
templates = {
template1: '<h1>Some HTML</h1>',
template2: '<h1>Some more HTML and a <%= variable %></h1>
...
}
This gets messy. Fast. So, I looked into RequireJS's text plugin and that makes it much cleaner. Now, I have a bunch of HTML files, and I essentially store it into my 'templates' object. Something like this:
define(['text!/templates/template1.html',
'text!/templates/template2.html',
...],
function(template1, template2, ...) {
return {
template1: template1,
template2: template2,
....
}
});
So now the issue is HTTP requests. For templates alone, I have 5 requests - 1 for the template.js file, and then 4 separate HTML template files. And that list is going to keep growing. One thing I was thinking was to put all of the HTML in one file, but that doesn't seem to go with the AMD methodology. As the app progresses, I can be a lot smarter about this and only load HTML templates when necessary - if they're all separate.
Is there any way around all of the HTML requests? I assume this is not good practice in a production environment.
Anyone have any other ideas for how to accomplish what I'm trying to do?
This is what the RequireJS Optimizer is for. It combines all of your modules into a single file as part of your pre-deploy build process. According to the README for the text plugin:
The text files are loaded via asynchronous XMLHttpRequest (XHR) calls, so you can only fetch files from the same domain as the web page (see XHR restrictions below).
However, the RequireJS optimizer will inline any text! references with the actual text file contents into the modules, so after a build, the modules that have text! dependencies can be used from other domains.
来源:https://stackoverflow.com/questions/22487868/templating-using-requirejs-text-js-plugin-and-underscore