Render templates in backbone using underscore.js

There are many ways to render html templates dynamically in a Backbone.js application and using Underscore.js is one of the simplest and best one. Full details are explained here. I have not gone into the depth of routers/models/view, but just providing a detailed explanation of this particular method.

Using Backbone and Underscore :

Backbone.js & Underscore.js

Folder Structure

The folder Structure can be as follows :

Root:
 ├───css
 ├───js
 │   ├───router.js
 │   ├───model.js
 │   ├───view.js
 │   └───config.js
 ├───templates
 │   ├───home.html
 │   ├───login.html
 │   └───register.html
 └───images
 └───index.html

Base Template

You will need to have a base template(index.html) within which you will be rendering the different templates. This will ensure that common html contents like hearder, footer, navigation menus etc are not loaded everytime a new page is rendered and thereby increasing the page loading speed drastically.

Sample structure can be as follows :

<html>
<head>
<!--Relevant CSS files-->
</head>
<body>
<div>
<div>
<!--HTML content for header-->
</div>
<div id="template">
<!--This would be where the dynamic content will be loaded-->
</div>
<div>
<!--HTML content for footer-->
</div>
</div>
<!--Include relevant JS Files-->
</body>
</html>

Note : Please note that you can decide on the structure of template as one wants. What i am using is a more general one so that everyone could relate to it easily.

———-

View

In your view, you can render a particular template to the base template as follows :

var LoginView = Backbone.View.extend({
el: "#template", //Container div inside which we would be dynamically loading the templates
initialize: function () {
console.log('Login View Initialized');
},
render: function () {
var that = this;</div>
<div>
//Fetching the template contents
$.get('templates/login.html', function (data) {
template = _.template(data, {}); //Option to pass any dynamic values to template
that.$el.html(template); //adding the template content to the main template.
}, 'html');</div>
<div>
}
});
var loginView = new LoginView();</div>
<div>

Note that the `el` tag is very important.

To pass values to view, simply pass it like :

var data_to_passed = "Hello";
$.get('templates/login.html', function (data) {
template = _.template(data, {
data_to_passed: data_to_passed
}); //Option to pass any dynamic values to template
that.$el.html(template); //adding the template content to the main template.
}, 'html');

And in the template :

<%=data_to_passed;>//Results in "Hello"

You can pass an array, object or even a variable.

Hope this has been helpful. Cheers

Leave a Reply

Your email address will not be published. Required fields are marked *