javascript - 下划线模板未获取值?

标签 javascript backbone.js underscore.js

因此,我很难将对象的数据放入下划线模板中。

JS

var details = SD.defaultView.extend({
    el: 'page',
    template: JST['app/www/js/templates/sex.ejs'],
    information: {
        header: 'some information!!!',
        image: '/img/path.jpg'
    },
    render: function () {
        var infom = _.template(this.template(), this.information);
        c(_.template(this.template()).source);
        this.$el.html(infom);
    }
});

JST 模板

<% console.info(this.information); %>
<sexform></sexform>

控制台输出

Object { header="some infromatoin!!!", image="/img/path.jpg"} global.js (line 34)
Object { header="some infromatoin!!!", image="/img/path.jpg"} global.js (line 34)

//output of c(_.template(this.template()).source);
function(obj){
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
__p+='<sexform></sexform>';
}
return __p;
}

现在,正如您所看到的,该对象是通过 this 传递的,但如果我尝试这样做,就会很有趣:

 <% c(this.information.header); %>
 <sexform></sexform>

出现以下错误:

TypeError: this.information is undefined  templates.js (line 21)
...__e = _.escape, __j = Array.prototype.join;function print() { __p += __j.call(ar...

这应该 100% 使用点表示法。

最佳答案

那是因为数据未定义!您传递的是 this.data 而不是 {data: this.data},因此模板的参数是 {header: '..', image: '.. '}

正确的代码是:

var wank = SD.defaultView.extend({
    el: 'page',
    template: JST['app/www/js/templates/sex.ejs'],
    data: {
        header: 'interesting!!!',
        image: '/img/path.jpg'
    },
    render: function () {
        // this line is changed
        var infom = _.template(this.template(), {data: this.data});
        this.$el.html(infom);
    }
});

编辑

template: JST['app/www/js/templates/sex.ejs'] 是已编译的模板,因此:

var infom = _.template(this.template(), {data: this.data});

错了,一定是

var infom = _.template({data: this.data});

关于javascript - 下划线模板未获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19392351/

相关文章:

javascript - 无法在 Chrome 中捕获 Chrome window.location.href

javascript - 如何将参数传递到 Backbone 集合并重置

javascript - 使用 jQuery Deferred 对象解决许多 Backbone 依赖关系

javascript - 如何使用 AngularJS 将数组转换为字符串 url?

javascript - Lodash方法检查一个数组中的所有元素是否在另一个数组中

javascript - jQuery/JavaScript 脚本不适用于 IE7

javascript - react - 让一个元素返回两个相邻的 <tr> 标签

javascript - 弹出onselect事件

javascript - Backbone.js:在 View 中的单击事件上应用 jQuery 类?

javascript - 将 JavaScript 数组中的对象合并为对象