遍历 html 模板中的数组字段

Iterate over array-field in the html-template

本文关键字:数组 字段 html 遍历      更新时间:2023-09-26

我有一个书签集合:

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

我该怎么做?

谢谢。

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

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

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

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

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

{{#each current_tag in tags}}
    <div> {{current_tag}} </div>
{{/each}}