Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js separate templates from html file

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!

like image 579
Abhilash M A Avatar asked Apr 05 '12 18:04

Abhilash M A


2 Answers

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

like image 113
Tamillharasan Avatar answered Nov 01 '22 10:11

Tamillharasan


Load them via xhr. The lib requirejs (requirejs.org) loads html file dependencies this way. This will work when in development, but the templates should be compiled into the js files in production.

like image 34
Trevor Avatar answered Nov 01 '22 08:11

Trevor