Skip to content

Instantly share code, notes, and snippets.

@jgb-solutions
Forked from leemeichin/README.md
Created April 1, 2017 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgb-solutions/7805a95e6cb53465017ce1cf3ead57c1 to your computer and use it in GitHub Desktop.
Save jgb-solutions/7805a95e6cb53465017ce1cf3ead57c1 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment