How to Define Custom Liquid Filters

Liquid Filters

In Liquid, filters are used to output formatted text in templates. Liquid provides a couple of standard filters, such as truncate which limits the length of the output to the number of characters given:

The first 50 characters of the main content are:
{{ page.body | truncate: 50 }}

In this example, page.body is the input to the truncate filter to which a number is passed as an argument.

Creating Your Own Filters

As a developer of a Rails Connector application, you can easily create your own filters you can then use in Liquid templates. Basically, a filter is just a method that takes at least one parameter and returns a processed string.

Here is how you would implement a filter that wraps a text in h1 tags:

module MyFilters

  def headline(input)
    "<h1>#{input}</h1>"
  end

end

In order for the Rails application to find your custom filters, you need to store them in the directory /app/filters. For the example above, the path would be /app/filters/my_filters.rb.

To use the above example in a template you would type the following:

{{ "Some Interesting Headline" | headline }}

This would produce:

<h1>Some Interesting Headline</h1>

Further Information

A good way to find inspiration in terms of how to implement custom filters is to read the source code of Liquid’s standard filters.