Sunday, July 21, 2013

Backbone view meets template

View meets templates

Existing model:
var Student = Backbone.Model.extend({
       defaults : {
              name : 'Ram',
              age : 22,
              score : 100
       }
}
Create a new inline template using the template attribute.
template: _.template("My name is  : <%= name %>  "),

Use this template using the below statement.

this.template(this.model.toJSON())

The above method this.template gets the dom content. The function model.toJSON() gets the model values in a json format. Finally it passes the model value to the template, the template attribute "name" will get replaced with the value present in the mode.
Full View code:

var StudentView = Backbone.View.extend({
       tagName: 'p',
       class: 'headClass',
       id: 'sViewId',
       template: _.template("My name is  : <%= name %>  "),
       initialize: function() {
              console.log('this is sort of a constructor');
              this.render();
       },
       render: function() {
              console.log('I am going to render');
              this.model = new Student();
              $(document.body).html(this.$el.html(this.template(this.model.toJSON())));
       }
});

var studentView = new StudentView();

Well, it is easy since the template content contains less code, but as the template code gets bigger and more template gets added, this becomes cumbersome to maintain.

So it would be great if the template code is still present in a separate file. This is called external templates.
Well, what do we need to do in order to create a new template.

This can be done by moving the template code to a script tag in a js file
<script id="nameTemplate" type="text/template" >
              <b>My name is  : </b> <%= name %>              
</script>
Modify the existing template to
              template: '#nameTemplate',
              var template = _.template(this.template());
              this.$el.html(this.template(this.model.toJSON()));



No comments:

Post a Comment