Twig inside Views in Drupal 8

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

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

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:
Drupal 8 solution

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 :)
Drupal 8 solution

{% if field_display_text2=='True' %}
  {{ field_text2 }}
{% else %}
  {{ field_text1 }}
{% endif %}

Conclusion

Twig makes frontend development 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.

[source: http://miromichalicka.com/2015/12/07/views-twig/]

The content of this field is kept private and will not be shown publicly.
Your email address will be kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.