Twig inside Views in Drupal 8

frontend for sitebuilders

Posted on December 7, 2015

Drupal 8 brings us except Symfony in backend also Twig for frontenders and Views for sitebuilders. Have you every thought about mixing this two parts of Drupal? In most of cases it is better if frontender knows at least basics of Drupal sitebuilding and Views are one of the most important modules for this.


Twig is templating engine which replaced PHPTemplates in Drupal 8. It uses some own functions, filters and syntax which aren’t related to PHP or Javascript and more importantly, it protects you from complexity of Drupal data model. No more thinking if variable is array or object - you access its children the same way. These functions and filters, which modify way how are input variables displayed. Drupal also extends Twig abilities by adding some own functions, mostly related to manipulation with html attributes. More about Twig should be found on this page and in Drupal change records.


Views is module, which knows probably everyone in Drupal world and honestly I cannot imagine building even simple presentation website without it. It offers you ability to build complex queries and display their results without having any knowledge about databases just through Drupal UI.

Using Twig functions filters in Views

Usecase: You want to display some text all uppercase and you don’t want to do it in CSS.

Drupal 7 solution: You can create field template with correct name, so it will have an effect only on desired field and inside this field template you will use strtoupper PHP function.

Drupal 8 solution: You will rewrite field with its own value and use upper Twig filter. It will look this way: upper Twig filter

More advanced Twig expressions

Usecase: Show content of field conditionally or conditionally show content one of two fields.

Drupal 7 solution: Preprocessing or some naughty things in templates.

Drupal 8 solution: Use Twig expressions :) upper Twig filter

1  {% if field_display_text2=='True' %}
2  {{ field_text2 }}
3  {% else %}
4  {{ field_text1 }}
5  {% endif %}


Twig makes Frontender’s life easier. I’m not saying that we should do everything possible only through UI, as I see there many risks related to harder debugging. Practical use on projects will show us the best way.