What is Twig?
Twig is a templating language for PHP that allows you to separate your application’s logic from its presentation. Unlike traditional PHP templates, which mix PHP code and HTML, Twig offers a more structured and readable syntax. It’s also secure, as it automatically escapes variables, reducing the risk of cross-site scripting (XSS) attacks.
In Drupal, Twig templates are used to generate the HTML markup for your site. Every piece of content, block, page, or other elements is rendered through a Twig template. By editing these templates, you can control the structure and style of your site's output.
Basic Twig Syntax
Variables
<h1>{{ page.title }}</h1>
This will display the page title
Filters:
<p>{{ user.name|upper }}</p>
The upper filter converts the user’s name to uppercase.
Control Structures:
{% if user.is_logged_in %}
<p>Welcome, {{ user.name }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
This checks if the user is logged in and displays a personalized message.
Comments:
{# This is a comment #}
Using Twig in Drupal
In Drupal, Twig templates are used to render the HTML for various components such as pages, nodes, blocks, and fields. These templates are stored in your theme’s templates directory and follow a specific naming convention based on the type of content they render.
Customizing the Node Template
Suppose you want to customize how a specific content type is displayed. Here’s how you can do it:
Locate the Template:
Open node--article.html.twig and modify it to change the structure or add custom classes.
<article class="node--{{ node.bundle }}">
<h1>{{ label }}</h1>
<div class="content">
{{ content }}
</div>
</article>
Clear Cache:
After making changes to your template, clear Drupal’s cache to see the changes.
Result:
Your article nodes will now use the custom template, allowing for unique styling and structure.
Enabling Twig Debugging
When working with Twig templates, it’s helpful to enable debugging. This feature shows you which template is being used for each part of the page, making it easier to customize your theme.
Edit services.yml:
Open sites/default/services.yml and add the following configuration:
Clear the cache to apply the changes.
Best Practices for Twig in Drupal
To get the most out of Twig in Drupal, follow these best practices
Keep Logic Out of Templates:
Avoid complex logic in Twig templates. Instead, use preprocess functions or custom modules to handle logic, leaving templates focused on presentation.
Use Theme Suggestions:
Take advantage of Drupal’s theme suggestion system to create specific templates for different content types, views, or even individual nodes.
Document Your Code:
Use Twig comments to explain your templates, making them easier to understand and maintain.
Leverage Drupal Variables:
Drupal provides a wealth of variables in its templates. Familiarize yourself with these variables to access all the data you need without adding extra logic.