Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment the counter inside a Liquid for loop?

Tags:

jekyll

liquid

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?

like image 518
dkrist Avatar asked Jan 01 '18 00:01

dkrist


People also ask

Can we increment inside for loop?

The for loop can proceed in a positive or negative fashion, and it can increment the loop control variable by any amount.

How do you increment a liquid in a variable?

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.

How do you double increment in a for loop?

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.


1 Answers

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 %}
like image 173
Alice Girard Avatar answered Sep 23 '22 06:09

Alice Girard