Underscore JS模板抛出Reference Error变量undefined

时间:2016-12-14 11:41:12

标签: node.js underscore.js

var resultTemplate = "" +
"    <ul class='searchList'>" +
"        <% _.each(paymentActions,function(paymentActivity){ %>" +
"            <li><span class='amount visible-phone'>-<%= paymentActivity.grossAmount %></span>" +
"            </li>" +
"        <% }); %>" +
"    </ul>";


var template = _.template(resultTemplate,{paymentActions : jsonData});

我得到的错误是(在代码段的最后一行): -

Uncaught ReferenceError: paymentActions is not defined(…)

如果我手动将json值放在var resultTemplate行而不是paymentActions,它可以正常工作。所以下面的代码执行正常: -

var resultTemplate = "" +
"    <ul class='searchList'>" +
"        <% _.each([{grossAmount:100},{grossAmount:200}],function(paymentActivity){ %>" +
"            <li><span class='amount visible-phone'>-<%= paymentActivity.grossAmount %></span>" +
"            </li>" +
"        <% }); %>" +
"    </ul>";

任何人都可以帮忙调试吗?

1 个答案:

答案 0 :(得分:1)

您最近可能升级了Underscore,_.template()函数的签名自1.7.0以来已changed

  

下划线模板不再接受初始数据对象。 _.template现在总是返回一个函数。

这是一个有效的版本:

&#13;
&#13;
var jsonData = [{grossAmount:100},{grossAmount:200}];

var resultTemplate = "" +
"    <ul class='searchList'>" +
"        <% _.each(paymentActions,function(paymentActivity){ %>" +
"            <li><span class='amount visible-phone'>-<%= paymentActivity.grossAmount %></span>" +
"            </li>" +
"        <% }); %>" +
"    </ul>";

var template = _.template(resultTemplate)({paymentActions : jsonData});

console.log(template);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
&#13;
&#13;
&#13;

区别在于:

var template = _.template(resultTemplate)({paymentActions : jsonData});