Shopify's Liquid templating language offers a wide range of filters that can help you manipulate and display data in your templates. Among these filters, math filters play a crucial role in performing calculations and formatting numerical data. We'll explore essential math filters in Liquid, including ceil, floor, basic arithmetic operations, and the modulo filter for customizing HTML classes.
Ceil and Floor Filters: Rounding Up and Down
The ceil and floor filters are used to round numbers up and down, respectively. These filters are particularly useful when you need to display whole numbers or manipulate data for calculations.
Ceil Filter: Rounds a number up to the nearest whole number:
{{ 3.2 | ceil }} {# Output: 4 #}
Floor Filter: Rounds a number down to the nearest whole number:
{{ 3.8 | floor }} {# Output: 3 #}
Basic Arithmetic Filters in Liquid
Liquid offers four basic arithmetic filters that can be used to perform calculations on numbers: divided_by, minus, plus, and times. These filters allow you to perform calculations and display the results directly in your templates.
divided_by: Divides a number by another number:
{{ 10 | divided_by: 2 }} {# Output: 5 #}
minus: Subtracts a number from another number:
{{ 10 | minus: 5 }} {# Output: 5 #}
plus: Adds a number to another number:
{{ 5 | plus: 5 }} {# Output: 10 #}
times: Multiplies a number by another number:
{{ 5 | times: 2 }} {# Output: 10 #}
Using the Modulo Filter for Custom HTML Classes
The modulo filter is used to calculate the remainder of a division operation. It can be particularly useful for applying custom classes to alternating HTML elements, such as table rows or list items.
For example, let's say you want to apply different background colors to even and odd rows in a table. You can use the modulo filter in combination with the forloop.index0 property to achieve this:
{% for product in collections.all.products %}
{% assign row_class = forloop.index0 | modulo: 2 %}
{% if row_class == 0 %}
{% assign row_class = 'even' %}
{% else %}
{% assign row_class = 'odd' %}
{% endif %}
{% endfor %}
In this example, we calculate the remainder of the division of forloop.index0 by 2 using the modulo filter. If the result is 0, the row is even, and we assign the 'even' class. If the result is not 0, the row is odd, and we assign the 'odd' class. This allows us to apply different styles to even and odd rows in our table, improving the readability of the content.
Liquid provides a variety of math filters to help you perform calculations, format numerical data, and customize the appearance of your templates. Explore the possibilities offered by these math filters and others that weren't included here. More math filters can be viewed on Shopify's documentation.
Having trouble? Ask for help.