如何在 underscore.js 模板中打印数组? [英] how to print array in underscore.js template?

查看:30
本文介绍了如何在 underscore.js 模板中打印数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 underscore.js 的模板库,但我不确定如何使用逻辑模板内部.例如,我想在模板中打印一组标签.最好的方法是什么?

Javascript:

bunny_data = {名称:洒",年龄:1,标签: ['模糊','wuzzy']};bunny_view = $("#bunny-template").html();$(body).append(_.template(bunny_view,bunny_data));

模板:

解决方案

您不需要像 @Ken 建议的那样封装 bunny_data,您走在正确的轨道上.是否要调用 _. 函数或仅使用纯 Javascript 结构取决于您,但 Underscore 模板中没有内置流结构,为此您只需嵌入代码(您可能想要研究 ecoMustache 或者你想要的东西)

我的例子看起来像这样(几乎和你的一样):

使用以下 Javascript:

bunny_data = {名称:洒",年龄:1,标签: ['模糊','wuzzy']};bunny_view = $("#bunny-template").html();$(body).append(_.template(bunny_view, bunny_data));

您可以在此处验证它是否运行.

(根据个人喜好,出于这个原因,除了模板之外,我是所有 Underscore 的重度用户,如果您有更复杂的用例,我对必须放入的代码量感到不舒服).

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>

解决方案

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):

<script type='text/template' id="bunny-template">
  <div> 
     <h5><%= name %></h5>
     <ul>
       <% for(var tag in tags) { %>
           <li><%= tags[tag] %></li>
       <% } %>
     </ul>
  </div>
</script>

with the following Javascript:

bunny_data = {
  name: "sprinkles",
  age: 1,
  tags: ['fuzzy','wuzzy']
};

bunny_view = $("#bunny-template").html();
$(body).append(_.template(bunny_view, bunny_data));

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).

这篇关于如何在 underscore.js 模板中打印数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆