nunjucks

Nunjucks: How to reach outside of loop that is looping through array to get 2nd value from another array


I'm trying to dynamically populate the data-cell attributes of the cells in a table row, along with the values of those cells in Nunjucks.

Here is my data:

{%- 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"
  }
]
-%}

And here is the row I'm trying to populate with data-cell attributes...

{%- 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 -%}

This solution works, but as you can see, I'm manually calling each one by index. Any thoughts?


Solution

  • Here's the solution. Hopefully this will help someone.

    {%- for item in rows -%}
    <tr>
      {%- for column in columns -%}
      <td data-cell="{{column.header}}">{{item[column.key]}}</td>
      {%- endfor -%}
    </tr>
    {%- endfor -%}