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:
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 gets no sanitization or formatting and should only be used for text that has already been prepared for HTML display.
Placeholder gets escaped to HTML and formatted using drupal_placeholder(), which makes it display as emphasized text.
The drupal_escape filter escapes a string for safe insertion into the final output. It is a replacement for Twig's default escape filter.
The safe_join filter joins several strings together with a supplied separator.
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.
The clean_class filter prepares a string for use as a valid HTML class name.
The clean_id filter prepares a string for use as a valid HTML ID.
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).