Backbone.js separate templates from html file
backbone.js, underscore.js
Solution
You can have templates in seperate html files and can load them as text using requirejs. There is a plugin called text which will help you to do that.
Example:
define([
'text!templates/sampleTemplate.html'
], function(tmpl){
var Sampleview = Backbone.View.extend({
id: 'sample-page',
template: _.template(tmpl),
render: function() {
$(this.el).html(this.template());
return this;
}
});
return SampleView;
});
The html file "templates/sampleTemplate.html" will be taken from the root path specified in the require.js config
Problem
I am working on a Backbone.js application. We are using underscore.js templates to load the contents to the View. Currently we have all the templates inside the index.html file, so the size of the file is increasing. Can anyone help me to find a solution for separating these templates to other files? Thanks in advance. EDIT Recently I have visited the Backbone patterns and I found that we can use JST templates to create separate template files for each template. They explained that we can create a `jst.js` file to put all our template code: ``` // http://myapp.com/javascripts/jst.js window.JST = {}; window.JST['person/contact'] = _.template( "<div class='contact'><%= name %> ..." ); window.JST['person/edit'] = _.template( "<form method='post'><input type..." ); <script src="http://myapp.com/javascripts/jst.js"></script> ``` Now all the templates are in the `jst.js` file. But if you have lots of templates and you want to move the templates to separate files you can create separate template files: ``` // http://myapp.com/javascripts/jst.js window.JST = {}; //http://myapp.com/javascripts/contactPerson.template.js window.JST['person/contact'] = _.template( "<div class='contact'><%= name %> ..." ); //http://myapp.com/javascripts/editPerson.template.js window.JST['person/edit'] = _.template( "<form method='post'><input type..." ); <script src="http://myapp.com/javascripts/jst.js"></script> <script src="http://myapp.com/javascripts/contactPerson.js"></script> <script src="http://myapp.com/javascripts/editPerson.js"></script> ``` Please let me know if there is any simpler idea. Thanks!