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:
{% assign i = i|plus:1 %}
.{% increment i %}
. 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?
The for loop can proceed in a positive or negative fashion, and it can increment the loop control variable by any amount.
Variables created using increment are independent from variables created using assign or capture . In the example below, a variable named “var” is created using assign . The increment tag is then used several times on a variable with the same name.
You can very easily increase the value by not using “++” operators but instead use “int i = 0;” (out of `for loop`) and do inside `for loop`: “i=i+2” which will add the value by 2. One way to achieve incrementing the value outside the for loop by not using “i=i+2” would be in the following way: #include <stdio.
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With