14

I am struggling to figure out how to increment the index variable within a for loop in Liquid/Jekyll. Currently, I have something along the lines of

{% for i in (0..num_posts) %}
    {% if i < some_value %}
        do_thing
    {% else %}
    {% endif %}
    {% assign i = i|plus:1 %}
    {% if i<some_value %}
        do_another_thing
    {% else %}
    {% endif %}
{% endfor %}

The problem is, instead of incrementing i, it leaves i as the same value.

Things I have tried:

  1. Using {% assign i = i|plus:1 %}.
  2. Using {% increment i %}.
  3. Using

    {% assign j = i|plus:1 %}
    {% assign i = j %}
    

I can't use the offset command either since the code doesn't always check only 2 if statements in the loop.

Any ideas?

dkrist
  • 149
  • 1
  • 1
  • 4

2 Answers2

28

Here i is not the index. To get the current index use {{ forloop.index }}.

{% if forloop.index < 5 %}
    Do something
{% endif %}

To assign your own custom index inside a loop you may use something like:

{% assign i = 0 %}
{% for thing in things %}
    {% assign i = i | plus:1 %}
{% endfor %}
Alice Girard
  • 2,077
  • 11
  • 21
4

Just use

{% increment my_counter %}

Creates a new number variable, and increases its value by one every time it is called. The initial value is 0. Also works with decrement. But just if you only have one simple counter, can't reset and always starts at "0"

Felix
  • 139
  • 1
  • 5