ronak_11
ronak_11

Reputation: 275

Backbone templating using underscore

I am learning backbone. I am facing an issue while using underscore.js for templating.
Following is the code.

var V = Backbone.View.extend({
    el: "body",
    render: function () {
        var data = {
            name: "MyName"
        };
        this.$el.html(_.template('<%= name %>', data));
        return this;
    }
});

var v = new V();
v.render();  

Output:

result

It should be :

MyName

Code - JSFiddle

Where am i going wrong?

Upvotes: 1

Views: 35

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240878

You need to invoke/evaluate the template with the data object as an argument.

Therefore it should be:

_.template('<%= name %>')(data);

or:

_.template('<%= name %>')({
  name: "MyName"
});

According to the documentation for the _.template function, you were passing the data object as an optional settings argument.

_.template(templateString, [settings]) 

Updated Example

var V = Backbone.View.extend({
    el: "body",
    render: function () {
        var data = {
            name: "MyName"
        };
        this.$el.html(_.template('<%= name %>')(data));
    }
});

var v = new V();
v.render();

Output:

MyName

Upvotes: 2

Related Questions