Change grid column after every 3 posts in Jekyll

Viewed 122

I want to display my blog posts in a 3x2x3 grid layout where the first row has 3 posts, the second row has 2 posts, and the third row has 3 posts. My method is just repeating the for loop using limit and offset to filter it. Trying to figure out a more elegant method to do this without using so many for loop.

Code

<div class='container'>
    <div class='row'>
        {% for post in site.posts limit: 3 %}
            <div class='col-sm-6 col-md-4'>
                <p>{{ post.title }}</p>
            </div>
        {% endfor %}

        {% for post in site.posts limit: 2 offset: 3 %}
            <div class='col-sm-6'>
                <p>{{ post.title }}</p>
            </div>
        {% endfor %}

        {% for post in site.posts limit: 3 offset: 5 %}
            <div class='col-sm-6 col-md-4'>
                <p>{{ post.title }}</p>
            </div>
        {% endfor %}
    </div>
</div>
1 Answers

You can use forloop.index to do this:

<div class='container'>
    <div class='row'>
        {% for post in site.posts limit: 8 %}
            <div class='col-sm-6{% unless forloop.index == 4 or forloop.index == 5 %} col-md-4{% endunless %}'>
                <p>{{ post.title }}</p>
            </div>
        {% endfor %}
    </div>
</div>

... but cycle is even more elegant:

<div class='container'>
    <div class='row'>
        {% for post in site.posts limit: 8 %}
            <div class='col-sm-6{% cycle "","",""," col-md-4"," col-md-4" %}'>
                <p>{{ post.title }}</p>
            </div>
        {% endfor %}
    </div>
</div>

... however if you want to show off/show that you are a true programmer, you should use the mathematical function modulo and start counting from zero with forloop.index0:

<div class='container'>
    <div class='row'>
        {% for post in site.posts limit: 8 %}
            {% assign mod = forloop.index0 | modulo: 5 %}
            <div class='col-sm-6{% if mod == 3 or mod == 4 %} col-md-4{% endif %}'>
                <p>{{ post.title }}</p>
            </div>
        {% endfor %}
    </div>
</div>
Related