27 Jan 2025

Using Math Filters and If Statements in Shopify Liquid: A Quick Guide

When working with Shopify themes, Liquid code allows you to create dynamic, customizable templates. One powerful feature of Liquid is its math filters, which let you manipulate numbers and add logic to your templates. Paired with if statements, math filters can be used for tasks like distinguishing between even and odd items in a list. Here’s how it works.

The Scenario

Imagine you want to loop through a section’s blocks and display different content depending on whether the block is in an even or odd position. You can achieve this using the modulo math filter and an if statement.

The Code

Below is an example of how to check if a block’s position is even:


{% for block in section.blocks %}
{% assign is_even = forloop.index | modulo: 2 %}
{% if is_even == 0 %} YES {% endif %}
{% endfor %}

Explanation

  1. The for Loop:
    The code starts by looping through all the blocks in a section using {% for block in section.blocks %}. This allows you to process each block individually.
  2. Using the modulo Math Filter:
    The forloop.index variable gives the current iteration number (starting at 1). By applying the modulo math filter (| modulo: 2), you can determine if the number is divisible by 2:

    • If the result is 0, the number is even.
    • If the result is 1, the number is odd.
  3. The if Statement:
    The if condition checks whether the result of the modulo operation is 0. If true, it outputs “YES,” signifying an even index.
  4. Outputting the Modulo Result:
    For demonstration purposes, the code also outputs the modulo result ({{ forloop.index | modulo: 2 }}), so you can see the logic in action.

Practical Use Cases

  • Styling Alternating Blocks: Use the even/odd logic to apply different styles to blocks. For example, even blocks could have one background color, and odd blocks another.
  • Conditional Content: Display specific content, such as banners or call-to-action buttons, only on certain blocks.

Final Thoughts

Shopify’s math filters and if statements open the door to more complex logic in your Liquid templates. With just a few lines of code, you can introduce functionality like alternating styles or dynamic content, making your storefront more engaging and visually appealing.

Try incorporating this logic into your own Shopify theme and experiment with how it can enhance your store’s design!

See all posts