如何在 underscore.js 模板中打印数组?
我正在使用 underscore.js 的模板库,并且我不确定如何使用 a 内部的逻辑模板。例如,我想在模板中打印一组标签。对此最好的方法是什么?
JavaScript:
bunny_data = {
name: "sprinkles",
age: 1,
tags: ['fuzzy','wuzzy']
};
bunny_view = $("#bunny-template").html();
$(body).append(_.template(bunny_view,bunny_data));
模板:
<script type='text/template'>
<div>
<h5><% = name %></h5>
<ul class='tag-list'>
<!-- How do I print the tags here? -->
</ul>
</div>
</script>
I am using underscore.js's templating library, and I am not sure how to go about using a logic inside of a template. for example, I would like to print an array of tags in a template. What is the best approach for this?
Javascript:
bunny_data = {
name: "sprinkles",
age: 1,
tags: ['fuzzy','wuzzy']
};
bunny_view = $("#bunny-template").html();
$(body).append(_.template(bunny_view,bunny_data));
Template:
<script type='text/template'>
<div>
<h5><% = name %></h5>
<ul class='tag-list'>
<!-- How do I print the tags here? -->
</ul>
</div>
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要像 @Ken 建议的那样封装
bunny_data
,您的方向是正确的。无论您是要调用_.
函数还是仅使用普通的 Javascript 构造都取决于您,但 Underscore 模板中没有内置的流程构造,为此您只需嵌入代码(您可能会想要研究 eco 或 Mustache< /a> 或者如果你想要的话 那)。我的示例如下所示(与您拥有的几乎相同):
使用以下 Javascript:
您可以在此处验证它是否运行。
(就个人喜好而言,我是除模板之外的所有 Underscore 的重度用户,因此,如果您有更复杂的用例,我对必须在其中放入的代码量感到不满意)。
You don't need to encapsulate
bunny_data
as @Ken suggests, you were on the right track. Whether or not you want to call_.
functions or just use plain Javascript constructs is up to you, but there's no built-in flow constructs in Underscore templates, to do that you just embed code (you might want to look into eco or Mustache or something if you want that).My example looks like this (almost the same as you own):
with the following Javascript:
You can verify that it runs here.
(On a personal preference note, I'm a heavy user of all of Underscore except the templates for this reason, I'm not comfortable with the amount of code you must put in them if you have a more complicated use case).
您似乎没有在 JavaScript 中正确设置
bunny_data
。而不是:
尝试:
打印模板中的数据(请注意,我删除了
<%= name %>
中 % 后面的空格):希望有帮助。
It looks like you are not setting
bunny_data
properly in your JavaScript.Instead of:
Try:
Print the data in your template (notice I removed the space after % in
<%= name %>
):Hopefully that helps.
另外
join
也能做到这一点,所以在 html 中你可以在 jsFiddle。
Also
join
will do the trick, so in html you'll haveCheck it at jsFiddle.