The Mijingo Blog

Latest news, updates, free tutorials, and more from Mijingo.

Filters in Twig and Craft

by Ryan Irelan

Filters in Twig and Craft allow you to alter the contents of a variable.

This could be a variable you set right in the template or one that is part of the data output provided by Craft (like when retrieving and looping through section entries).

Filters are applied right in the output tag, like this:


{{ variable | filter }}

and separated using the pipe character.

Here’s an example where we want to title case the string that is assigned to the variable.


{% set page_title = "an important news story" %}
{{ page_title | title }}

When outputting the contents of the page_title variable, we are running it through the title filter in Twig. This filter adjusts the string to title case, so every word starts with a capital letter.

It will output:

An Important News Story

Another very practical filter that you might use frequently is trim. This filter strips out whitespace at the beginning and end of a string.


{% set page_title = " an important news story " %}
{{ page_title | trim }}

That will remove the whitespace at the beginning and end of the string.

You can also trim specific characters by specifying them in parentheses.


{{ page_title | trim('.') }}

The previous example outputs:

an important news story

which is missing the title casing we did before.

Let’s add in both filters together. We do that by chaining together them with pipes.


{{ page_title | trim | title }}

That outputs:

An Important News Story

Craft-specific Filters

Pixel & Tonic created some special filters just to use in Craft. These filters won’t be listed in the Twig documentation, and, similarly, the Craft documentation won’t list all of the Twig filters. This is a situation where you’l need to refer to two different sets of documentation.

Here are a couple Craft filters that I find interesting:

  • markdown - processes the string passed to it using the Markdown library.
  • group - allows you to group array items together based on a common property that you define. The Craft docs have a great example of sorting the entries returned from a Craft section by the year of the entry.

Ready to learn more about the Craft CMS?

My Craft Starter Pack is 4 ½ hours of premium learning that will get you started building sites with Craft for yourself, your company, or your clients.

Get Immediate Access

Filed Under: Craft CMS, Twig