3

I am trying to use the for loop in Jekyll to render sample data. I can reference the markdown objects or whatever they are called directly, but when I use a for loop it doesn’t work. Here’s an example of the problem I am having:

markdown file with data:

tests:  
  test1:  
    number: 1 . 
  test2:  
    number: 2 . 
  test3:  
    number: 3 . 

sessions.html:

<p>{{ page.tests.test1.number }}</p>
<p>{{ page.tests.test2.number }}</p>
<p>{{ page.tests.test3.number }}</p>

This outputs to:

<p>1</p>
<p>2</p>
<p>3</p>

If I do this instead:

{% for test in page.tests %}
  <p>{{ test.number }}</p>
{% endfor %}

I get:

<p></p>
<p></p>
<p></p>

I can even do this:

{% for test in page.tests %}
  <p>{{ test }}</p>
{% endfor %}

And get:

<p>test1{"number"=>1}</p>
<p>test2{"number"=>2}</p>
<p>test3{"number"=>3}</p>

Any idea what I am doing wrong?

juzraai
  • 5,693
  • 8
  • 33
  • 47
Brock Tillotson
  • 119
  • 1
  • 8

1 Answers1

5

Take a look at this:

{% for test in page.tests %}
  <p>{{ test.number }}</p>
{% endfor %}

You are iterating over page.tests. Since page.tests is a hash and not a list, you are iterating over the key-value pairs of that object. (See this topic).

The keys are test1, test2 and test3, you can access them with test[0].

But you need the value, in this case you can use test[1], and to get the number, you can call test[1].number:

{% for test in page.tests %}
  <p>{{ test[1].number }}</p>
{% endfor %}

And you will get the same output as in your first example.

Or, instead of test1, test2 and test3, you may try to define a list:

tests:
  - number: 1
  - number: 2
  - number: 3

This way, your code will work too:

{% for test in page.tests %}
  <p>{{ test.number }}</p>
{% endfor %}
juzraai
  • 5,693
  • 8
  • 33
  • 47