Search code examples
rubyjekyllliquidcycle

Modulus (or lack thereof) in Ruby's Liquid templating engine


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?


Solution

  • For your specific example, you could use {% cycle 'close rows': nil, '</div>', '</div>' %} after the {% endfor %}.