【问题标题】:Backbone templating using underscore使用下划线的主干模板
【发布时间】:2015-11-29 18:52:44
【问题描述】:

我正在学习骨干。我在使用 underscore.js 进行模板时遇到问题。
以下是代码。

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();  

输出:

result

应该是:

MyName

代码 - JSFiddle

我哪里错了?

【问题讨论】:

  • @mu 太短了:backbone.js 上的金色徽章@ oh man @___@

标签: javascript backbone.js underscore.js


【解决方案1】:

您需要使用data 对象作为参数调用/评估模板。

因此应该是:

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

或:

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

根据documentation for the _.template function,您将data 对象作为可选设置参数传递。

_.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();

输出:

MyName

【讨论】:

  • 请注意 before Underscore 1.7 你可以说 _.template(tmpl, data) 来获取 HTML。仍然有很多过时的代码和教程。
猜你喜欢
  • 2012-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多