1
votes

I'm teaching myself Jekyll and Liquid and was wondering how do you get indexed items of an array?

I can create an array of page.tags and loop through them:

{% assign tags = pages.tags %}
{% for tag in tags %}
{% endfor %}

But say there are four tags and I want to access tag at index 2. I've seen some code like this:

{% for i in 1...page.tags %}

{% endfor %}

But I can't seem to get the index to work, these fail:

{% for i in 1...page.tags %}
    <p>{{page.tags[i]}}</p>
{% endfor %}

{% for i in 1...page.tags %}
    <p>{{i}}</p>
{% endfor %}
2

2 Answers

2
votes

I improved your code slightly:

<div id="topNav">
  <ul>
    {% for tag in page.tags %}
      {% if forloop.first %}         
        <li class="fadeIn firstItem notLogo">{{tag}}</li>
      {% else %}
        <li class="fadeIn notLogo">{{tag}}</li>
      {% endif %}
    {% endfor %}
  </ul>
</div>

Source: https://help.shopify.com/en/themes/liquid/objects/for-loops

0
votes

I've solved it with a kind of hack.

<div id="topNav">

    <ul>

        {% assign count = 0 %}

        {% for tag in page.tags %}
            {% if count == 0 %}         

                <li class="fadeIn firstItem notLogo">{{tag}}</li>

            {% else %}

                <li class="fadeIn notLogo">{{tag}}</li>

            {% endif %}
            {% assign count = count | plus: 1 %}

        {% endfor %}

    </ul>


</div>