Hero Image

Twig Filters for Drupal 8

Twig Filters for Drupal 8

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).

Steve Lavigne

President

Steve is a passionate storyteller who thrives on challenging the status quo. He is an avid researcher with a keen analytical mind able to strategize on technology, sales and marketing decisions by analyzing data and behaviours across various industries and technologies.

Ottawa

135 Laurier Ave. West, Suite 100
Ottawa, ON K1P 5J2
TEL: 1 (877) 257-6746

Saratoga Springs

153 Regent Street
Saratoga Springs, NY 12866
TEL: 1 (877) 257-6746