The problem: if you need to use view templates in a small-to-large Backbone application, defining your templates in JavaScript code will be unwieldy and difficult to maintain.
Solution: You may need put the templates in a JavaScript file.
Your app will need to serve a dynamically-created JavaScript file that compiles your files.
A common JST file will create the JST
object (in the window namespace), with
each of its members defined as template functions. In this example, we’ll use
Underscore’s _.template
, which returns functions.
// 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..."
);
You will then need to link to this JavaScript page in your HTML.
<script src="http://myapp.com/javascripts/jst.js"></script>
In your JavaScript code, simply access the JST object’s members to access the views.
var html = JST['person/edit']();
var dict = { name: "Jason", email: "j.smith@gmail.com" };
var html = JST['person/contact'](dict);