javascript - 引用错误 : variable is not defined with underscore template

标签 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);
    });

类别模板:

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

我不明白为什么你看不到模板中的变量

最佳答案

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

关于javascript - 引用错误 : variable is not defined with underscore template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26086217/

相关文章:

javascript - THREE.js:远处光源转换的阴影

javascript - 如何在 querySelector 的帮助下更改背景图像

javascript - underscorejs 将带冒号的字符串传递给它时,会根据环境呈现不同的结果

javascript - js中信息检索哪个更快?对象与计算

javascript - 循环遍历对象数组并仅获取少数对象

javascript - 如何使用 UnderscoreJS 通过 'id' 联合/合并两个集合

javascript - 如果浏览器中没有操作,如何关闭 Bootstrap 模式

javascript - 表格上清晰的结果

jquery - 如何从 ASP.NET MVC cshtml 获取授权信息并将其设置为 jquery ajax 的 Headers ["Authorization"]

javascript - 如何检查 window.open() 打开同一页面两次