I'm working on a Jekyll site and am trying to output three column divs nested in a row div. Liquid makes this pretty easy with their cycle
filter:
{% for p in site.categories.post %} {% cycle 'add rows': '<div class="row">', nil, nil %} <div class="column"> <a href="{{ p.url }}">{{ p.title }}</a> </div> {% cycle 'close rows': nil, nil, '</div>' %} {% endfor %}
However, this only really works when there are 3, 6, 9, etc. posts. When the total number of posts is not a multiple of three, the <div class="row">
never gets closed--the for loop ends before the closing tag can be output as part of the close rows
cycle.
In Ruby, PHP, or any other language I could easily fix this with a modulus operator, so in addition to close rows
cycle I would output </div>
when if site.categories.size % 3 == 0
. However, Liquid, because it's a safe templating language, doesn't support the modulus.
What else can I do to properly close <div class="row">
when the total number of posts is not a multiple of three?
I've found this way to work great!
{% assign mod = forloop.index0 | modulo:4 %} {% if mod == 0 %} <!-- Do stuff --> {% endif %}
For your specific example, you could use {% cycle 'close rows': nil, '</div>', '</div>' %}
after the {% 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