如何使用主JSON中的变量查找第二个JSON数据集 - 使用Handlebars?

时间:2014-06-14 01:33:30

标签: javascript json handlebars.js

我有两个数据集 - 一个定义页面的包含项目,另一个是具有更深层数据的更大数据集。但是为此我们可以说 - 第一个JSON数据集(让我们称之为 page.json

{
 "title": "pageTitle here",
 "description": "Content here",
 "items": [
  {
   "id": 14,
   "name": "Bob"
  },
  {
   "id": 11,
   "name": "Dave"
  },
  {
   "id": 12,
   "name": "Fred"
  },
 ]
}

第二个JSON数据集(让我们称之为 data.json )包含

[
 {
  "id": 14
  "name": "Bob Matthews",
  "description": "Some description here about Bob",
  "age": 24,
  "location": "Sydney"
 },
 {
  "id": 11
  "name": "Dave Smith",
  "description": "Some description here about Dave",
  "age": 23,
  "location": "Sydney"
 },
 {
  "id": 12
  "name": "Fred Williams",
  "description": "Some description here about Fred",
  "age": 42,
  "location": "Sydney"
 }
]

现在我的模板中有类似

的内容
<!-- loop through each person for this page from page.json -->
{{#each page}}
  <!-- lets find the data for this person from the data.json and display it -->
  {{#compare page.id data.id}}
   <h2>{{data.name}}</h2>
   <p>Description {{data.description}}</p>
   <p>Age {{data.age}}</p>
   <p>Location {{data.location}}
  {{/compare}}
{{/each}}

但是这不起作用......是否有某种方式没有构建自定义手柄助手从第二个JSON中的数组中查找(然后显示数据)项目数据来源?

注意:这是针对使用Assemble.io&amp; Grunt从JSON数据集构建静态页面

由于

1 个答案:

答案 0 :(得分:0)

我没有对此进行过测试,但您是否尝试在data.json中循环查看列表,以找到与page.json中当前元素匹配的元素。代码可能需要一些tweeking,因为我只是真正处理过YAML Front Matter,而且我不熟悉如何使用* .json文件。

{{#each page.items}} <!-- loop through each person for this page from page.json -->
    {{#each data}}   <!-- loop through each person in list from data.json -->
        <!-- In here '../page' refers to the page in previous scope -->
        <!-- and 'this' refers to the current element in data.      --> 

        <!-- lets find the data for this person from the data.json and display it -->
        {{#compare ../page.id this.id}}
            <h2>{{this.name}}</h2>
            <p>Description {{this.description}}</p>
            <p>Age {{this.age}}</p>
            <p>Location {{this.location}}    
       {{/compare}}

    {{/each}} <!-- end data loop -->
{{/each}}     <!-- end page.items loop -->