Personally, we needed a reliable solution in my company, so we went with:
- Require.js - to load the module.
- Handlebars - for more powerful templates than Underscore can offer
- HBS is a great plugin from Alex Sexton that handles compiled templates with Require
With this setting, I can save all my templates in my own file, and then, to use them, I have these files:
define(['template!path/to/someTemplate'], function(someTemplate) { var MyNewView = BaseView.extend({template: someTemplate}); $('body').append(new MyNewView().render().el); }
(and, as you might have guessed, we have a basic Backbone view called BaseView that uses the view template property to render the view).
Now, all that is said, if you do not need such a reliable setup, then the Requirement may not be for you. In this case, I would do the following:
Put all your templates in one or more HTML files; wrap them in script tags, for example:
<script id="dummyTemplate" type='text/template'> <span>I'm a template!</span> </script>
Write code on your server side to include these HTML files in the main HTML file that you send to the client.
Write a function that takes a template identifier, receives the text of this element, compiles it into a template, and returns this template (maybe cache compiled templates if you want ... of course, using Underscore templates, I donβt think you even need compilation, so you can skip all this).
Use your function to access your templates: $("#something").html(templateFunc('dummyTemplate').template())
This will allow you to store your templates in html files (for syntax coloring), but at the same time they are convenient to use in JS. You can also split your templates between the number of files you want, as long as you can write the inclusion logic to bring them.
If you prefer Require, be sure to check out the HBS plugin. And if you haven't looked at Handlebars templates yet, you might want to; they are much more powerful than Underscore (but, like any good template system, don't allow too much logic).
source share