ReferenceError:变量未使用下划线模板定义

时间:2014-09-28 15:02:14

标签: javascript jquery underscore.js

我正在使用jQuery,jQueryMobile和下划线模板制作应用程序,但我从未遇到过此错误,我找不到模板中发生的变量:

    self.$list = $("#list");
    var template = _.template('<%= foo %>', {foo: 'hello'});
    self.$list.html(template);

错误:ReferenceError:未定义foo

这是一个例子,如果我尝试渲染类别列表,我感觉相同。

    _.each(categories, function(category){
        console.log(category); //<-- ok
        var template = _.template(self.$categoryTemplate.text(), category);
        self.$list.append(template);
    });

categoryTemplate:

    <script id="category-template" type="text/template">
        <li><a href="#"><% = name %></a></li>
    </script>

我不明白为什么你没有在模板中看到变量

1 个答案:

答案 0 :(得分:2)

调用_.template会返回一个函数,该函数将带有模板变量的对象作为第一个参数。

所以你应该这样做:

self.$list = $("#list");
var template = _.template('<%= foo %>')({foo: 'hello'});
self.$list.html(template);

和此:

_.each(categories, function(category){
    console.log(category); //<-- ok
    var template = _.template(self.$categoryTemplate.text())(category);
    self.$list.append(template);
});
相关问题