Edward
Edward

Reputation: 1508

Iterate over array of items in Jekyll Frontmatter

My front matter:

menu_links:
- donate: "/donate"
- shop: "/shop"

My loop:

{% for menu_link in page.menu_links %}
  <div><a class="menu-item" href="{{ menu_link[1] }}">{{ menu_link[0] }}</a></div>
{% endfor %}

What am I doing wrong here?

Upvotes: 1

Views: 1499

Answers (2)

Edward
Edward

Reputation: 1508

Solution:

{% for menu_link in page.menu_links %}
  {% for item in menu_link %}
    <div><a class="menu-item" href="{{ item[1] }}">{{ item[0] }}</a></div>
  {% endfor %}
{% endfor %}

Each item needs to be looped through a second time in order to get the key/value pair of each menu_link.

Upvotes: 1

marcanuy
marcanuy

Reputation: 23982

The way it is defined is parsed as: [{"donate"=>"/donate"}, {"shop"=>"/shop"}]

so you would be able to access them with:

{{page.menu_links[0]['donate']}}
{{page.menu_links[1]['shop']}}

A better one would be:

menu_links:
 donate: "/donate"
 shop: "/shop"

so you can access directly:

{{page.menu_links['donate']}}
{{page.menu_links['shop']}}

then your original code would work.

Upvotes: 2

Related Questions