Nunjucks:如何到达循环数组的循环外部以从另一个数组获取第二个值

问题描述 投票:0回答:1

我正在尝试动态填充表格行中单元格的数据单元格属性,以及 Nunjucks 中这些单元格的值。

这是我的数据:

{%- set columns = [
  {
  "header": "Beverages",
  "key": "name",
  "sortable": true
  },
  {
  "header": "Cost",
  "key": "cost",
  "sortable": true
  },
  {
  "header": "Text",
  "key": "text",
  "sortable": true
  },
  {
  "header": "Date",
  "key": "date",
  "sortable": true
  }
]
-%}

{%-
set rows = [
  {
  "id": 1,
  "name": "Water",
  "cost": 100,
  "text": true,
  "date": "05021967",
  "unsortable": "12 Fountain Street, Andover, MA"
  },
  {
  "id": 2,
  "name": "Soda",
  "cost": 250,
  "text": false,
  "date": "12121963",
  "unsortable": "23 Oakland Avenue, Louisville, KY"
  },
  {
  "id": 3,
  "name": "Coffee/Tea",
  "cost": 50,
  "text": true,
  "date": "03111964",
  "unsortable": "4 Maple Road, Stone Mountain, GA"
  }
]
-%}

这是我尝试用数据单元格属性填充的行...

{%- for item in rows -%}
<tr>
<td data-cell="{{columns[0].header}}">{{item.name}}</td>
<td data-cell="{{columns[1].header}}">{{item.cost}}</td>
<td data-cell="{{columns[2].header}}">{{item.text}}</td>
<td data-cell="{{columns[3].header}}">{{item.date}}</td>
</tr>
{%- endfor -%}

此解决方案有效,但如您所见,我通过索引手动调用每个解决方案。有什么想法吗?

nunjucks
1个回答
0
投票

解决方案如下。希望这会对某人有所帮助。

{%- for item in rows -%}
<tr>
  {%- for column in columns -%}
  <td data-cell="{{column.header}}">{{item[column.key]}}</td>
  {%- endfor -%}
</tr>
{%- endfor -%}
© www.soinside.com 2019 - 2024. All rights reserved.