【问题标题】:Iterate over array-field in the html-template遍历 html 模板中的数组字段
【发布时间】:2013-10-08 20:25:40
【问题描述】:

我有收藏书签:

> db.Bookmarks.find()
{ "Name" : "Lenta.ru", "Timestamp" : 1381233418275, "URL" : "http://lenta.ru", "_id" : "zS2ccZXkGLENzN2Bx", "tags" : [  "asdx" ] }
{ "Name" : "Another", "Timestamp" : 1381234763188, "URL" : "http://ya.ru", "_id" : "qAB46c38hEFSw3NTE", "tags" : [  "one",  "two" ] }

“标签”字段具有数组类型。

我有一个 HTML 模板来遍历书签:

<template name="bookmarks">
    {{#each bookmarks}}
          <a href="{{URL}}" class="bookmark_url">{{Name}}</a>
          <div> {{tags}} </div>
        {{/each}}
</template>

我想将每个标签显示到一个单独的“div”中。像这样的:

<template name="bookmarks">
    {{#each bookmarks}}
          <a href="{{URL}}" class="bookmark_url">{{Name}}</a>
          {{#each tags}}
             <div> {{current_tag}} </div>
          {{/each}}
        {{/each}}
</template>

我该怎么做?

谢谢。

【问题讨论】:

  • 代替 {{current_tag}},{{this}} 有效吗?此外,最好让每个标签都成为一个带有 _id 的对象(即使你生成它)——Spark 喜欢这样
  • 是的,{{this}} 工作正常。谢谢。你能创建答案,我会接受吗?你能解释一下吗:'另外最好让每个标签都是一个带有_id的对象(即使你生成它)'?没看懂。
  • 我会尽快发布答案。至于_id,这里解释比较好:fogofcode.wordpress.com/2013/03/26/…

标签: javascript meteor


【解决方案1】:

迭代简单数组时,使用{{this}} 访问每次迭代的值。

{{#each tags}}
  <div>{{this}}</div>
{{/each}}

我建议将您的 tags 数组转换为对象数组,例如:

"tags": [{_id: "1", "somevalue"}, {_id: "2", "someothervalue"}]

当涉及唯一 ID 时,Spark 渲染引擎能够更好地决定何时重绘 #each 的内容。参考:http://fogofcode.wordpress.com/2013/03/26/on-the-importance-of-_id-when-iterating-with-each-in-handlebarsmeteor/

【讨论】:

    【解决方案2】:
    {{#each current_tag in tags}}
        <div> {{current_tag}} </div>
    {{/each}}
    

    【讨论】:

    • 它不起作用。我可以查看 {{#each}} 块之外的所有元素,但里面什么都没有(即使我在里面放了静态文本)。
    猜你喜欢
    • 2021-05-20
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 2011-02-06
    • 2016-01-18
    • 2018-05-24
    • 2020-01-12
    • 2014-07-15
    相关资源
    最近更新 更多