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

How do I look up a second JSON data set using a variable in primary JSON - using Handlebars?

本文关键字:JSON 数据集 第二个 查找 使用 Handlebars 变量 何使用      更新时间:2023-09-26

我有两个数据集——一个定义了页面包含的项,另一个是包含更深层次数据的更大的数据集。这里我们有第一个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,从JSON数据集构建静态页面

谢谢

我还没有测试过这个,但是您是否尝试过循环data.json中的列表以找到与page.json中当前元素匹配的元素。代码可能需要一些调整,因为我只真正处理过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 -->