【问题标题】:Rendering nested Collection with meteor js template使用流星 js 模板渲染嵌套集合
【发布时间】:2014-08-02 04:29:36
【问题描述】:

我是 JavaScript 和 Meteor 的新手。我设法设置了所有服务器端通信,但不知道如何在我的集合中呈现数据块。就是这样:

{"NAME1":{"service":"NAME1","count":0,"maxCount":0},"NAME2":{"service":"NAME2","count":1,"maxCount":1},"NAME3":{"service":"NAME3","count":2,"maxCount":2},"NAME4":{"service":"NAME4","count":3,"maxCount":3},"NAME5":{"service":"NAME5","count":4,"maxCount":4},"NAME6":{"service":"NAME6","count":5,"maxCount":5}}

我可以通过调用标签名称来提取这个块。在那之后,我被困住了。每个 NAME 作为键都是一个动态字符串,我只知道值是数组 - 服务、计数和 maxCount,我希望这些值以 3 列的表格格式显示 - 名称、计数和最大值。我可能应该使用光标进行此块渲染,但不知道该怎么做。请帮忙。

我要渲染的 JSON 块在“p”标签内

<template name="template_name">
<h2> Data </h2>
   {{#each all_blocks}}
     {{#with block_i_need }}
        <p>"block i need: " {{.}}</p>
      {{/with}}
    {{/each}}
</template>`

如何将 block_i_need 传递给函数并返回 service、count 和 maxCount 值?

【问题讨论】:

    标签: javascript html json templates meteor


    【解决方案1】:

    您可以使用_.values 提取对象的值数组。

    Template.whatever.services = function() {
      var object = getThatJsonBlockSomehow();
      // object is {"NAME1":{"service":"NAME1","count":0,"maxCount":0}, ...};
      return _.values(object);
      // returns [{"service":"NAME1","count":0,"maxCount":0}, ...]
    }
    

    然后,在模板中,您可以使用 #each 来迭代该数组。 (#each 允许您遍历数组或游标。)

    <template name="whatever">
      <table>
        <tr>
          <th>Service</th><th>Count</th><th>Max count</th>
        </tr>
        <!-- iterate over the [{"service":"NAME1","count":0,"maxCount":0}, ...] array -->
        {{#each services}}
          <tr>
            <td>{{service}}</td><td>{{count}}</td><td>{{maxCount}}</td>
          </tr>
        {{/each}}
      </table>
    </template>
    

    【讨论】:

    • 非常感谢。我想我的 javascript 真的很糟糕 :( 我再次被困在从我的收藏中获取这个 json 块。请参阅上面的编辑。非常感谢帮助。
    • 所以,我将正确的 json 块传递给 _.value() 并收到错误“队列任务中的异常”并且没有显示任何内容。似乎我将整个块传递给该值,而不仅仅是“NAME1”:{“service”:“NAME1”,“count”:0,“maxCount”:0}。我想我需要进一步分解这个 json 块。
    猜你喜欢
    • 2012-06-16
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    相关资源
    最近更新 更多