我在这里做错了,但我看不到!我试图在下划线模板中循环一个数组。虽然它不起作用,所以我遗漏了一些东西,这是我的代码,我的模板可以正常工作,否则只是 _.each 东西在窃听:
<script type="text/template" id="PageContent">
<div class="col2">
<@ _.each([0,1,2,3,4], function(i) { @> <p><@ i @></p> <@ }); @>
</div>
</script>
我也做了一些这样的模板设置:
_.templateSettings = {
interpolate: /\<\@(.+?)\@\>/gim
};
最佳答案
因为您只在自定义模板设置中定义了插值正则表达式,所以下划线不知道何时评估表达式。当您定义自定义模板设置时,您需要定义并区分插值和评估。从下划线 template()
文档:
Define an interpolate regex, and an (optional) evaluate regex to match expressions that should be inserted and evaluated, respectively. If no evaluate regex is provided, your templates will only be capable of interpolating values.
在标准(无自定义设置)模板中,区别在于评估:
<% %>
和值插值:<%= %>
.因此,例如,您上面的模板应该是(使用标准模板设置):
<% _.each([0,1,2,3,4], function(i) { %> <p><%= i %></p> <% }); %>
如果您想继续使用自定义设置,您还需要在 _.templateSettings 中定义评估正则表达式。根据您的问题和评论,例如:
_.templateSettings = {
interpolate: /\<\@\=(.+?)\@\>/gim,
evaluate: /\<\@(.+?)\@\>/gim
};
然后更新您的模板以使用围绕代码块的评估表和围绕值的插值表,如下所示:
<script type="text/template" id="pageContent">
<div class="col2">
<@ _.each([0,1,2,3,4], function(i) { @> <p><@= i @></p> <@ }); @>
</div>
</script>
来源:http://documentcloud.github.com/underscore/#template
关于backbone.js - underscore.js 模板中的每个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7361185/