Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 708
Andrew Avatar asked Feb 11 '10 16:02

Andrew


2 Answers

I've found this way to work great!

{% assign mod = forloop.index0 | modulo:4 %} {% if mod == 0 %}    <!-- Do stuff --> {% endif %} 
like image 117
Dehli Avatar answered Oct 13 '22 22:10

Dehli


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

like image 44
Grant Husbands Avatar answered Oct 13 '22 21:10

Grant Husbands