0
votes

I have a nested yaml data file for my jekyll blog like so:

Nickname1:
      name: John
      address: Johnstreet 1

Nickname2:
     name: Rudolf
     address: Rudolfstreet 1

I use this to print additional information after each post, which I specify in the front matter. This works fine.

I now wish to create a site that lists all entries of this data file. This should in theory be easy:

{% for nickname in site.data.NAMEOFFILE %}
    <li> {{ nickname.address }} </li>
{% endfor %}

However, this does not work because the YAML data is nested. The data has to remain nested, and each entry needs to have a different nickname. The problem with that is of course that I am unable to loop over all entries, because they are all differently named.

Can you folks help me out here? Is there any way in which I can achieve this without changing the nested structure of my data file? Changing the nested structure would break large parts of my site.

Thanks in advance.

1

1 Answers

0
votes

Jekyll data files can be set up in two formats: list or dictionary (not the official terminology, but that's what I call them and what helps me understand them).

Lists are used for iteration. Dictionaries are used for looking up an individual item and shouldn't be used in iteration.

// list.yml
- nickname: Nickname1
  name: John
  address: Johnstreet 1

- nickname: Nickname2
  name: Rudolf
  address: Rudolfstreet 1

...

// usage
{% for person in site.data.list %}
    <li> {{ person.address }} </li>
{% endfor %}
// dictionary.yml
Nickname1:
  name: John
  address: Johnstreet 1

Nickname2:
  name: Rudolf
  address: Rudolfstreet 1

...

// usage
{% assign person = site.data.dictionary['Nickname1'] %}
<ul>
    <li> {{ person.address }} </li>
</ul>

I have the same data in two different files: one in a list format and one in a dictionary format. That lets me iterate or do specific lookups whenever I need. Drawbacks are that you have duplicated data across two different files and need to maintain consistency whenever you make changes.

To solve your specific problem, I would make another data file with the data formatted into a list so that you can iterate through the data. This means you don't need to change the file with the nested structure and can avoid breaking the site.

Jekyll docs example on 'dictionary' usage

Jekyll docs example on 'list' usage