Even though templates are not part of Backbone.js, I believe it’s critical to have a basic understanding of templates. Templates are a core component that will be used with Backbone.js Views.
Templates will help us separate code from the HTML markup. When MVC is discussed in regards to server side (Ruby on Rails, ASP.NET MVC) the “V” is for view. Views are implemented different in Backbone than in most server side technologies. On the server side, views should be extremely dumb and very little logic if any should be include.
Very, Very Simple Template
In the previous code we have a reference to jQuery and Underscore.
There is a single
On the next line we created another variable called compileTemplate1. The template is compiled to a function that can be evaluated later.
Template using Substitution
In this next example we will substitute values.
So in this example we are passing in a variable (data2) when we execute the compileTemplate function.
So first we create a variable called data2. This variable is a data object with a property called title. The title property includes a value called “Title2”
We then create a template that includes a variable called title. The title variables in the template is surrounded by “<%= … %>“. So as you can tell, the title property in variable data2 is the same as the title variable in the template.
We compile the template the same as we did in the previous example. Nothing changed here.
Now when we call compileTemplate2, we pass in the variable data2. We can see in the results that the value in data2 was substituted with the variable in the template.
Template with Non-Inline
That’s it for the most part.
For more information on Underscore Templates please see – http://underscorejs.org/#template
Also you can view the code using jsFiddle.net website at http://jsfiddle.net/BarDev/mGwBL/