underscore.js 模板中的每个循环
我在这里做错了什么,但我看不到它!我试图在下划线模板中循环数组。但它不起作用,所以我错过了一些东西,这是我的代码,我的模板工作正常,否则,只是 _.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
};
I'm doing something wrong here but I can't see it! Im trying to loop an array in a underscore template. It doesn't work though so I'm missing something, Here's my code, my templates work fine otherwise, it's just the _.each stuff that's bugging out:
<script type="text/template" id="PageContent">
<div class="col2">
<@ _.each([0,1,2,3,4], function(i) { @> <p><@ i @></p> <@ }); @>
</div>
</script>
I've also done some template settings like this:
_.templateSettings = {
interpolate: /\<\@(.+?)\@\>/gim
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您仅在自定义模板设置中定义了插值正则表达式,因此 underscore 不知道何时计算表达式。当您定义自定义模板设置时,您需要定义并区分插值和评估。来自下划线
template()
文档:在标准(无自定义设置)模板中,区别在于评估:
<% %>
和值插值:<%= %>
。因此,例如,上面的模板应该是(使用标准模板设置):
如果您想继续使用自定义设置,您还需要在 _.templateSettings 中定义一个评估正则表达式。根据您的问题和评论,例如:
然后更新您的模板以使用围绕代码块的评估形式和围绕值的插值形式,如下所示:
来源:http://documentcloud.github.com/underscore/#template
Because you've only defined an interpolation regex in your custom template settings, underscore doesn't know when to evaluate expressions. When you define custom template settings you need to define and differentiate between interpolation and evaluation. From the underscore
template()
documentation:In a standard (no custom settings) template the difference is evaluation:
<% %>
and value interpolation:<%= %>
.So, for example, your template above should be (with standard template settings):
If you want to continue using custom settings you'll need to define an evaluation regex in _.templateSettings as well. Based on your questions and comments something like:
And then update your template to use the evaluation form around code blocks and the interpolation form around values, like so:
source: http://documentcloud.github.com/underscore/#template