June 05, 2024
Essential modules for working with Twig in Drupal There are two contributed Drupal modules that streamline
There are two contributed Drupal modules that streamline website development when working with Twig templates. Additionally, with a custom module, we can also extend the capabilities of this template engine.
Essential Modules for Working with Twig in Drupal
The following two contributed modules expand the vocabulary of Twig functions and filters available in the Drupal core to increase developer productivity:
- Twig tweak: Adds functions to print blocks, views, entities, fields, images, tokens, etc., in the Twig templates of our project. On the official module page on drupal.org, there is a linked reference manual (Cheat sheet). In this manual, we can find the documentation of all the functions defined by this module, accompanied by a practical example for each of them.
- Twig Field Value: Adds filters so that, when printing a specific field, you can access its label, value, properties (text_format, alt, url, …), or the entity it references. On the official module page on drupal.org, we can find practical examples of how to use it.
Finally, we must be aware that we can also program our own Twig extension in a custom module. This process is simple:
- We program a class “NOMBRECLASSE” that inherits from “AbstractExtension” within the file “src/Twig/Extensions/NOMBRECLASSE.php” of an existing or newly created module. Then, we will have to declare our functions within the “getFunctions” method and our filters within the “getFilters” method. The rest of the implementation details can be quickly understood by reviewing the source code of either of the two modules we have analyzed in this article.
- We declare the Twig extension “NOMBRECLASSE” that we programmed in the previous point in the file “NOMBREMODULO.services.yml” of our module.
Share