Backbone.js separate templates from html file

I am working on a Backbone.js application. We use underscore.js templates to load content into a view. Currently, we have all the templates inside the index.html file, so the file size is increasing. Can someone help me find a solution to split these patterns into other files? Thanks in advance.

EDIT

I recently visited Backbone patterns , and I found that we can use JST to create separate template files for each template. They explained that we can create a jst.js file to fit all of our boilerplate 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 many 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 a simpler idea. Thanks!

+7
source share
2 answers

You can have templates in separate html files and load them as text using requirejs . There is a plugin called text to help you with this.

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 config.ht.conf.

+7
source

Download them via xhr . The lib requirejs (requirejs.org) loads the dependencies of the html files this way. This will work during development, but the templates must be compiled into js files during production.

+1
source

All Articles