image of man on a laptop in a field
Twig Filters for Drupal 8
I was very excited when the community decided to use Twig as the new template engine for Drupal 8. Twig offers many performance and security improvements to Drupal. Additionally, it is a flexible template engine, allowing us to extend the base features (tags, filters), and create our own.

Over the last few weeks, I’ve been busy upgrading an existing theme to Drupal 8. As part of the process, I’ve had to become familiar with Twig and how it was extended to meet the needs of Drupal 8.

What is a Twig filter?

Twig variables can be modified by filters. Filters are separated from the variable by a pipe symbol (|) and may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.

I’ve decided not to include information regarding the standard Twig filters within this article, only the new filters created specifically for Drupal 8.  The following Twig filters are available within Drupal 8:

t

The t filter will run the variable through the Drupal t() function, which will return a translated string. This filter should be used for any interface strings manually placed in the template that will appear for users.

passthrough

Passthrough gets no sanitization or formatting and should only be used for text that has already been prepared for HTML display. 

placeholder

Placeholder gets escaped to HTML and formatted using drupal_placeholder(), which makes it display as emphasized text.

drupal_escape

The drupal_escape filter escapes a string for safe insertion into the final output. It is a replacement for Twig's default escape filter.

safe_join

The safe_join filter joins several strings together with a supplied separator.

without

The without filter creates a copy of the renderable array and removes child elements by key specified through arguments passed to the filter. The copy can be printed without these elements. The original renderable array is still available and can be used to print child elements in their entirety in the twig template.

clean_class

The clean_class filter prepares a string for use as a valid HTML class name.

clean_id

The clean_id filter prepares a string for use as a valid HTML ID.

format_date

The format_date filter prepares a timestamp for use as a formatted date string.

If you are interested in learning about the standard filters in Twig, please see “Twig for Template Designers” (http://twig.sensiolabs.org/doc/templates.html#filters).

Navy blue plain colour background

As Founder and CEO, Chris lives and breathes the paradigm that OPIN was founded on: Open Innovation. This mantra has helped our founder grow OPIN from its roots to Canada's fastest-growing digital agency. Chris is considered a thought leader in the entrepreneurship, open-source and government communities.

Let our industry experts take the drivers seat and discuss the flexibility and extensibility of Drupal
#833394