简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM