Twig Templating Tutorial
Introduction to Twig
Twig is a modern template engine for PHP, which is flexible, fast, and secure. It is primarily used in the Drupal content management system to create and manage themes. This tutorial will guide you through the basics of Twig templating, with practical examples and explanations.
Getting Started with Twig
To use Twig in Drupal, ensure you have a compatible version of Drupal installed. Twig templates are typically found in the templates
directory of your theme.
Example directory structure:
/themes/custom/mytheme/
├── templates/
│ ├── page.html.twig
│ └── node.html.twig
└── mytheme.info.yml
Creating a Simple Twig Template
Let’s create a simple Twig template called example.html.twig
. This template will render a title and a body.
example.html.twig:
<h1>{{ title }}</h1>
<p>{{ body }}</p>
In this example, {{ title }}
and {{ body }}
are placeholders for variables passed to the template.
Using Variables and Filters
Twig allows you to use variables and apply filters to manipulate the output. For example, you can capitalize text using the capitalize
filter.
Using a filter:
<p>{{ content|capitalize }}</p>
Control Structures
Twig provides control structures such as if
, for
, and block
to control the flow of templates.
Example of an if statement:
<{% if user.is_logged_in %}>
<p>Welcome, {{ user.name }}!</p>
<{% else %}>
<p>Please log in.</p>
<{% endif %}>
Extending Templates
You can extend templates in Twig to create a base template that other templates can inherit from. This is useful for maintaining a consistent layout across your site.
Base template (base.html.twig):
<html>
<head><title>{% block title %}My Site{% endblock %}</title></head>
<body>
<header>Header Content</header>
<main>{% block content %}{% endblock %}</main>
</body>
</html>
Child template:
<{% extends 'base.html.twig' %}>
<{% block title %}Child Page Title{% endblock %}>
<{% block content %}>
<p>This is the content of the child template.</p>
<{% endblock %}>
Conclusion
Twig templating is a powerful way to manage the presentation layer in Drupal. By utilizing variables, filters, control structures, and template inheritance, you can create dynamic and maintainable templates for your Drupal site.