jsonstatic-sitenunjuckseleventy

Iterate over global data subfolder in Eleventy / 11ty


I'm using Eleventy and have created the subfolder yummy in my global data folder, that contains the following files:

\src\_data\yummy\drinks.json
\src\_data\yummy\food.json

When I use {{ yummy | dump }} I get the following output:

{
  "drinks":[
    {"name":"Milk","price":5},
    {"name":"Water","price":1}
  ],
  "food":[
    {"name":"Pizza","price":4},
    {"name":"Hot dog","price":2},
    {"name":"Sallad","price":1},
    {"name":"Avocado","price":3}
  ]
}

I want to create a list with all entries in both json-files. I almost have achieved this with the following loop:

<ul>
{% for key, val in yummy %}
<li>{{ val[0].name }} cost {{ val[0].price }}$</li>
{% endfor %}
</ul>

However, since I'm using [0], the output is only the first entry in each json-file:

- Milk cost 5$
- Pizza cost 4$

I want all entries and have tried the following, but get no output at all:

<ul>
{% for key, val in yummy %}
<li>{{ val[key].name }} cost {{ val[key].price }}$</li>
{% endfor %}
</ul>

Solution

  • Managed to solve this myself by adding a second loop.

    <ul>
      {% for key, val in yummy %}
        {% for entry in val %}
        <li>{{ entry.name }} cost {{ entry.price }}$</li>
        {% endfor %}
      {% endfor %}
    </ul>
    

    Outputs as:

    - Milk cost 5$
    - Water cost 1$
    - Pizza cost 4$
    - Hot dog cost 2$
    - Sallad cost 1$
    - Avocado cost 3$