Describe the Liquid filter, and give an example of how it’s used.

The Liquid filter is a key feature of the Liquid templating language, used for transforming output and modifying variables in a flexible way. Filters are applied to variables in templates to change or format the output. They can be used to manipulate strings, numbers, arrays, and even control structures. Filters are typically written with a pipe (|) symbol between the variable and the filter.

How it Works:

  • The basic syntax for using a filter is:

    liquid
    {{ variable | filter_name }}
  • Filters can also be chained together to apply multiple transformations:

    liquid
    {{ variable | filter_name | another_filter }}

Common Types of Filters:

  • String filters: For manipulating text.

    • upcase: Converts a string to uppercase.

    • downcase: Converts a string to lowercase.

    • capitalize: Capitalizes the first letter of the string.

    • truncate: Truncates a string to a specified length.

  • Date filters: For formatting dates.

    • date: Formats a date according to a given format.

    • time: Outputs the time part of a date.

  • Number filters: For formatting numbers.

    • plus: Adds a value to the number.

    • minus: Subtracts a value from the number.

    • round: Rounds the number to the nearest integer.

  • Array filters: For manipulating arrays.

    • size: Returns the number of items in an array.

    • first: Returns the first element of the array.

    • last: Returns the last element of the array.

Example Usage:

1. String Manipulation:

liquid
{{ "hello world" | upcase }}

Output: HELLO WORLD

2. Date Formatting:

liquid
{{ "2025-04-18" | date: "%B %d, %Y" }}

Output: April 18, 2025

3. Number Arithmetic:

liquid
{{ 5 | plus: 10 }}

Output: 15

4. Array Handling:

liquid
{% assign fruits = "apple, orange, banana" | split: ", " %}
{{ fruits | first }}

Output: apple

This shows how you can modify data in a Liquid template to fit the needs of your output, whether for simple formatting, arithmetic, or complex string and array manipulation.