We use cookies to make your viewing experience better. By accepting you consent, you agree to our Cookie policy

Accept
Improve your Craft CMS skills

Understanding The Craft CMS Twig Filters

10 min read
Understanding The Craft CMS Twig Filters

Twig filters are a powerful but often misunderstood feature of Craft CMS. This guide will explain everything you need to know: what Twig filters are, how to use them, and real-world examples to apply in your own templates. Read on to master filters for transforming variables, arrays, dates, and more using best practices to write cleaner, leaner templates in Craft.

Twig filters transform variables in Craft CMS templates. Built-in filters format strings, dates, arrays, and more. Custom filters extend functionality. Best practices: limit chaining, comment on complex logic, and focus on key tasks. Compared to PHP, Twig filters favour simplicity and clean code over heavy data manipulation suited better for PHP functions.

The Twig Template Language

Overview of Twig

Twig is a powerful template engine used by Craft CMS to separate presentation logic from business logic. Rather than embedding PHP code within HTML files, Twig allows you to write cleaner templates focused purely on displaying data.

Some key advantages of using Twig for templating include:

  • Improved security - Twig sandboxes templates and prevents direct execution of PHP code. This reduces vulnerabilities like XSS attacks.

  • Separated display and logic - Twig templates contain only presentational logic and markup. The controllers handle any business logic required. This promotes cleaner code.

  • Extensible with filters and functions - Twig offers filters for transforming variables and functions for reusable logic. Developers can also create custom filters and functions.

  • Designed for templates - Twig was created specifically for templating. The syntax is optimized for writing display logic and HTML markup.

Overall, Twig provides an efficient, extensible and secure templating language perfect for the requirements of Craft CMS.

Role of Twig in Craft CMS

Twig forms the backbone of the templating system in Craft CMS. All template files use the .twig file extension and must contain Twig syntax like variables, tags, filters etc.

Some examples of common Craft CMS template files built with Twig include:

  • index.twig - The main template displayed on site pages. It extends and includes other templates.

  • _layout.twig - The base layout template containing shared header, footer etc. Extended by index.twig.

  • _entry.twig - Template for rendering individual entries. Included in index.twig.

  • _macros.twig - Contains reusable Twig macros. Imported into other templates.

The Twig templating engine processes these templates to generate the final HTML displayed to visitors. It combines multiple templates through extension and inclusion to build complete pages.

Craft CMS handles passing data to the templates and executes any business logic required. Twig focuses only on logically displaying this data in the markup. This separation of concerns is a major benefit of using Twig.

Advantages of Using Twig

Twig provides several important advantages when used for templating in Craft CMS:

Separation of Display and Logic

Twig templates contain only presentational logic - how to display data in the markup. The controllers handle any business logic required. This promotes cleaner and more maintainable code.

Security

Twig sandboxes templates to prevent direct execution of PHP code. Variables must be passed in by controllers. This prevents XSS and other vulnerabilities. Twig auto-escapes variables too for protection against code injection.

Extensibility

Twig offers filters for transforming variables and functions for reusable logic in templates. Developers can also create custom filters and functions tailored to their needs.

Cleaner, Designer-Friendly Templates

Twig's syntax is optimized for writing display logic and markup. Designers can easily understand and tweak Twig templates even without programming knowledge.

Easy Adoption

Twig uses simple, sensible syntax familiar to those who've used templating languages like Liquid or Jinja. This shallow learning curve makes adopting Twig easy for teams.

In summary, the advantages Twig provides including security, extensibility, and cleaner templates make it an ideal templating engine for Craft CMS.

Understanding Twig Filters

What are Twig Filters?

Twig filters are functions that modify variables and output in Twig templates. They allow you to transform and alter data right within your templates.

Some examples of common built-in Twig filters include:

  • upper - Converts a string to uppercase

  • date - Formats a date variable

  • replace - Replaces parts of a string

  • round - Rounds a number to a given precision

These filters provide reusable logic you can apply to variables by using the pipe (|) symbol. For example:

{{ product.name|upper }}

{{ post.date|date('F jS, Y') }}

Filters are a key part of what makes Twig so powerful and extensible.


How Twig Filters Work

Twig filters are applied to variables using the pipe (|) symbol. You can chain multiple filters together:

{{ var|filter1|filter2 }}

The output of one filter is passed to the next filter in the chain.

For example:

{{ "mystring"|upper|replace({'MYSTRING':'Hello'}) }}

{# Outputs: Hello #}

Here the upper filter capitalizes the string, then replace substitutes the uppercase string.

Some filters accept arguments to configure their behaviour:

{{ product.price|currency('GBP') }}

This passes 'GBP' as an argument to the currency filter.

You can also apply filters within filter logic using the apply tag:

{% apply upper|replace({'FOO':'bar'}) %}

This text

{% endapply %}

This allows you to avoid repetition when applying the same filters to large blocks of content.

Types of Built-in Twig Filters

Twig includes many built-in filters across several categories:

Text Filters

Text filters modify strings and text content. For example capitalize, title, truncate.

Array Filters

Array filters manipulate arrays. Like first to get the first element, last for the last element.

Date Filters

Date filters format Date/time variables. You can use date to style dates or time to format times.

Mathematical Filters

Math filters perform numeric operations like abs for absolute value and round for rounding numbers.

URL & HTML Filters

Filters like url_encode, json_encode and striptags help output variables into URL strings,

JSON or by removing HTML.

Other Filters

Misc. filters like default to assign default values and merge to combine arrays.

There are dozens of built-in filters covering a diverse range of use cases. The Twig documentation contains a full list of every filter available.

When you need to transform, format or manipulate a variable, chances are there is a Twig filter that can handle it. These built-in filters are one of the main advantages of using Twig for templating.

Using Twig Filters in Craft CMS

Accessing Twig Filters

One of the biggest advantages of using Twig for templating in Craft CMS is access to all the built-in Twig filters.

These filters can be accessed from any Twig template just by using the pipe (|) symbol after a variable. For example:

{{ entry.postDate | date('F jS, Y') }}

This takes the postDate variable and passes it through the date filter to format it.

All of Twig's core filters like date, upper and replace are available out of the box.

Additionally, Craft CMS includes some custom Twig filters tailored for common use cases:

  • search - Creates search excerpt highlights

  • sanitize - Sanitizes text content

  • sanitizeUrl - Sanitizes URLs into valid links

These Craft-specific filters supplement the core Twig filters.

Craft CMS Specific Filters

Here are some examples of useful Twig filters that come bundled with Craft CMS:

search

The search filter creates highlighted excerpts from search results:

{{ entry.body|search(query, hightlightTag) }}


sanitize

sanitize strips disallowed HTML tags from content:

{{ entry.body|sanitize }}

sanitizeUrl

sanitizeUrl converts URLs into valid links:

{{ string|sanitizeUrl }}

Other Craft filters include encode for encoding special characters, footnotes for parsing footnotes, and filter for filtering arrays.

These custom filters enable templating scenarios unique to Craft CMS. And they nicely complement the standard Twig filters available.

Importing Filter Libraries

If even more filters are needed, additional libraries can be imported into Craft templates.

For example, to access the Twig Intl filters:

{% import _self as filters %}

{{ text|filters.localizeddate('full', 'none', locale) }}

Here we imported the library into a filters namespace to access the localizeddate filter.

Some other useful extensions to import include Twig Extra for string filters and Twig Date for advanced date handling.

Craft even has a plugin store where custom Twig filter libraries can be downloaded and imported into projects.

Importing these external packages expands the range of filters available beyond Craft's built-in filters. More filters means more ways to manipulate and output variables within Twig templates.

Best Practices for Twig Filters

Performance Considerations

When working with Twig filters, it's important to keep performance implications in mind. Chaining together too many filters, especially those that manipulate large amounts of content like replace and merge, can become costly as each filter's output must be processed before moving to the next. Similarly, applying filters repeatedly within large for loops or across big content blocks can add up quickly.

To optimize filter chains, try to limit them to only 3-4 key filters where absolutely necessary. Make use of the apply tag to encapsulate complex filter logic rather than chaining which tends to hurt performance. Also avoid sorting directly in your templates via filters, opting instead to sort earlier in your business logic if possible. Overall, keeping filter usage lean and efficient avoids excessive strain on template rendering.

Commenting and Testing Filters

Due to Twig's chained syntax, complex filter logic can often become unclear down the road. Adding descriptive comments for any complicated or ambiguous filter chains is wise.

Thoroughly test filtered variables to confirm you receive the expected output, debugging any issues by inspecting the intermediate values passing through each filter stage.

Well-documented and validated filter logic remains understandable and maintainable over time.

Avoiding Overuse of Filters

While Twig filters enable transforming variables within templates, be wary of overusing them for minor presentational tweaks better suited to CSS styling rules.

For example, avoid excessive string replacement filters purely for formatting data or generic logic that controls visual design rather than content. Instead, focus filter usage on key functionality like formatting dates, sanitizing content for output, filtering or sorting arrays, and other transformations where actually needed. Keeping business logic in controllers and presentation details in stylesheets promotes proper separation of concerns. Use Twig filters judiciously where they provide the most value.

Common Uses and Examples

Formatting Text

Twig offers many handy text formatting filters that transform string variables in useful ways. For example, capitalize and lower can be used to easily modify text case, with capitalize capitalizing just the first letter while lower makes the entire string lowercase.

Truncate allows limiting strings to a maximum number of characters, which is perfect for generating excerpts. Replace substitutes one string with another, enabling find-and-replace actions right in templates. Striptags strips HTML tags from content strings to output just text. These are just a few of the many text formatting filters available for handling string variables.

Working with Dates/Times

Several Twig filters help format date and time variables stored in common formats. The date filter styles date in a variety of display formats like "F jS, Y" for "March 10th, 2020". The time filter takes a DateTime and outputs just the time portion formatted as a string like "08:35".

Date_modify enables manipulating dates by adding or subtracting intervals like days or hours.

For even more robust date handling, the Twig Date Extension provides advanced filtering capabilities. Overall, Twig makes working with dates and times in templates simple and intuitive.

Array Manipulation

For array data, Twig filters enable directly manipulating arrays right within templates. Sort can alphabetize or numerically order arrays on the fly. Reverse handles reversing array order quickly.

Slice returns just a subset slice of items from an array. First and last filters conveniently get just the first or last item from an array. Additional filters like merge and filterBy give even more options for working with array data in templates. The array manipulation powers of Twig filters make templating complex lists of data much easier.

Comparing Twig Filters vs. PHP

Performance Differences

When it comes to performance, Twig filters and standard PHP functions have tradeoffs depending on use case.

For simple text formatting and manipulation, Twig filters like capitalize and truncate are often faster since they avoid the overhead of PHP function calls.

However, for more complex operations like HTML manipulation or sanitization, native PHP functions can be faster as they are implemented in the native language runtime.

Additionally, applying filters in large for loops may incur a performance penalty compared to PHP where you have more control over optimization.

So for straightforward formatting, Twig filters tend to have a performance edge. But PHP pulls ahead for heavy data manipulation.

Separation of Logic

A key difference between Twig filters and PHP is separation of display logic.

Twig filters focus purely on transforming data for presentation in templates. The controllers handle any business logic required.

PHP functions intermix logic and display code. Complex formatting logic can obscure the presentation code.

So Twig filters promote cleaner templates by decoupling logic and view layers. But PHP provides more power for complex logic in the template itself.

Use Case Recommendations

Simple Formatting

For straightforward tasks like capitalization, escaping, or date/number formatting, prefer Twig filters for their terse, intent-revealing syntax and performance.

Heavy Data Manipulation

For intensive operations like XML/HTML sanitization or modification, PHP's speed and flexibility outweighs Twig filters.

Complex Logic

If significant logic is needed in display logic, PHP allows keeping it self-contained. Twig forces logic to controllers.

Presentational

When display focused, use Twig filters to separate logic and promote cleaner code.

Evaluate tradeoffs like performance vs. separation of concerns for optimal choice between PHP vs. Twig filters.

Shape April 2022 HR 202
Andy Golpys
- Author

Andy has scaled multiple businesses and is a big believer in Craft CMS as a tool that benefits both Designer, Developer and Client. 

Share
Feedback
Show us some love
Email Us
We usually reply within 72 hours
Agency Directory
Submit your agency
Affiliate Partners
Let's chat