How can I iterate over items from the Jekyll / Liquid collection in batch 3?

I have a basic HTML structure where I am displaying 3 elements per line. To separate them correctly, I use 2 borders (first / second second / third), as in the following diagram:

ITEM1 | ITEM2 | ITEM3

      

is defined using SASS as follows:

         .middle {
                position: relative;
                z-index: 1;

                &:before {
                    content: '';
                    width: 32px;
                    height: 100%;
                    position: absolute;
                    left: -24px;
                    top: 0;
                    display: block;
                    z-index: -1;
                    box-shadow: 32px 0 0 0 #fff, 0 -32px 0 0 #fff, 0 32px 0 0 #fff, 32px 32px 0 0 #fff, 32px -32px 0 0 #fff, 0 0 32px 0 rgba(0, 0, 0, 0.15);
                }

                &:after {
                    content: '';
                    width: 32px;
                    height: 100%;
                    position: absolute;
                    right: -24px;
                    top: 0;
                    display: block;
                    z-index: -1;
                    box-shadow: -32px 0 0 0 #fff, 0 -32px 0 0 #fff, 0 32px 0 0 #fff, -32px 32px 0 0 #fff, -32px -32px 0 0 #fff, 0 0 32px 0 rgba(0, 0, 0, 0.15);
                }
            }

      

I would like to differentiate between these three inline elements when I iterate over the Jekyll collection. To paraphrase, iterate from 3 to 3. This I just started learning Jekyll a couple of hours ago and I could see there are filters available, but I don't know how to achieve this in a standard iteration with the following type:

{% for item in array %}
    {{ item }}
{% endfor %}

      

https://gist.github.com/smutnyleszek/9803727

+3


source to share


1 answer


In order to be able to group elements in a row during iteration, we use a filter modulo

:

Separates the output with a number and returns the remainder.

We can then identify each iteration and, more specifically, which of the three elements we are processing by doing forloop.index | modulo: 3

:

If the remainder is 1, this is the first element in the line, if it is 2, then it is the second, if it is 0, it will be the third. for example iterating through an arraysite.posts



{% for post in site.posts %}
{% assign mod = forloop.index | modulo: 3 %}
{{ mod }}:{{post.title}}
{% if mod == 1 %}
<div>first item</div>
{% elsif mod == 2 %}
<div class="middle">second item</div>
{% else %}
<div>third item</div>
<hr>
{% endif %}
<br>
{% endfor %}

      

Please note that based on your code, I have applied the middle

css class to the second element.

This will lead to the output:

 1:First post title
first item

2:Second post title
second item

0:Third post title
third item

-----------------

1:Fourth post title
first item

      

+3


source







All Articles