Skip to content

Instantly share code, notes, and snippets.

@leemeichin
Created April 12, 2012 12:02
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save leemeichin/2366832 to your computer and use it in GitHub Desktop.
Save leemeichin/2366832 to your computer and use it in GitHub Desktop.
Modulo Liquid filter for Jekyll

Modulo Liquid filter for Jekyll

Got nested columns in your grid-based Jekyll site?

Wondered why you didn't have a way to calculate the modulo inside your posts loop to open and close your 'rows' containing those nested columns?

Add this filter to your _plugins directory, and use it like so:

{{ x | mod:y }}

Note: Liquid will return this as a string, so be aware of that when using comparisons.

What about an actual example for nesting those columns?

{% for post in site.posts %}
  
  {% capture modulo %}{{ forloop.index0 | mod:3 }}{% endcapture %}

  {% if modulo == '0' or forloop.first %}
    <div class="row">
  {% endif %}

    <!-- don't forget those pesky 'alpha' and 'omega' tags if they're in there -->
    <div class="three-columns {{ cycle 'alpha', '', 'omega' }}">
      ... POST STUFF ...
    </div>

  {% if modulo == '2' or forloop.last %}
    </div>
  {% endif %}

{% endfor %}

Adapt to suit the specific framework. For something like Skeleton, you might prefer one-third column.

# Modulo filter for Jekyll
#
# Adds modulo functionality to Jekyll. It's already in the Liquid core, but that
# version doesn't appear to be in Jekyll.
#
# That's about it.
module Jekyll
module ModuloFilter
# Returns the modulo of the input based on the supplied modulus
# Called 'mod' to avoid conflict with newer Liquid's 'modulo' filter
def mod(input, modulus)
input.to_i % modulus.to_i
end
end
end
Liquid::Template.register_filter(Jekyll::ModuloFilter)
@rajakhoury
Copy link

Thanks alot man very helpful

@albertvolkman
Copy link

@rajakhoury please be aware that this is directly available within Liquid now-

https://shopify.github.io/liquid/filters/modulo/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment