Jekyll Front Matter Array Index access

Hi, guys,

Thank you for clicking this ticket,

On Front Matter

---
layout: archive

lang: en

ref:
- xl430-w250
- xc430-w150
---

Mark Down

{% for sec in page.ref %}

{{ sec }}  <-- This works 

{{ sec[0] }} <-- This does not work.. 

{% endfor %}

Is there any way to access the index of the particular array?

Thank you :slight_smile:

When using the Liquid {% for %} tag, you have access to the loop index via the forloop object.
The index of the current item iterated can output by {{ forloop.index }}
(Note: It starts with 1 instead of 0).

Hi, Thank you for your advice.

Unfortunately, it does not work…

Front Matter

layout: archive
ref:
  - ref1: "xl430-w250"
  - ref2: "xc430-w150"
  - ref3: "xh430-w210"

Markdown

{% for reference in page.ref %}

{{ reference.index[1] }} 

{{ reference.index1 }}

{{ reference.index 1 }}

{{ reference.1 }}

{% endfor %}

:scream:

Regarding the first section

---
layout: archive

lang: en

ref:
- xl430-w250
- xc430-w150
---

If you want to use [0] index then don’t do it on a for loop.

Here you can get the first element of the array

{{ page.ref[0] }}
1 Like

Regarding the 2nd case, you defined a list of hashes when I think you just want a hash. Note lack of leading dashes

ref:
  ref1: "xl430-w250"
  ref2: "xc430-w150"
  ref3: "xh430-w210"

Then can do

{% for r in page.ref %}
- Key {{ r[0] }} - Value {{ r[1] }}
{% endfor %}

The zero and one indexes are to unpack the r item…

As your frontmatter will be converted from YAML to a Ruby object stored like this.

{ "ref1": "x1430-w250"}

And when you use the for loop it becomes an array (or a tuple) of exactly two elements.

["ref1", "x1430-w250"]
1 Like

I think you misunderstood my comment.
I suggested that you use {{ forloop.index }} explicitly.

---
lang: en
ref:
- xl430-w250
- xc430-w150
---

{% for item in page.ref %}
  {{ forloop.index }}. {{ item }}
{% endfor %}

2 Likes