Theming
Topic

Template Design with Twig for Drupal 8, 9, and 10

Twig is a template engine for PHP, which is the language used in Drupal. Twig can be used for templates in generic PHP applications as well as Drupal themes. The Drupal implementation of Twig is the same as regular Twig with a couple of Drupal additions. Drupal adds some custom filters and automatically handles the render pipeline for you. Anything you can do in regular Twig you can also do in Drupal's implementation of Twig.

Example tasks

  • Customize markup in templates for a Drupal site
  • Use dynamic data from variables within template files
  • Customize markup in PHP applications that use Twig for templates

Confidence

Resources on this page use both generic PHP applications as well as template files from Drupal 8 themes for context and examples. The Twig that is used in generic PHP applications can be used in Drupal templates as well. Note that Drupal has extended Twig and provides some Drupal-specific filters and functions. In some cases, these Drupal-specific functions or filters are preferable to their generic Twig counterparts.

Note: Drupal 10 uses Twig 3.x. (Drupal 9 uses Twig version 2.x and Drupal 8 uses Twig version 1.x. Be sure to use the appropriate version when consulting Twig's official documentation.

Drupalize.Me resources

Categories
Drupal 8, 9, and 10
More information

Twig is the default template engine for Drupal. If you want to make changes to the markup that Drupal outputs you're going to need to know at least some Twig. In this tutorial, we will outline the role that Twig now plays in Drupal, how Twig impacts the theming experience, and where to find additional resources for learning Twig.

At the end of this lesson, you'll be able to:

  • Describe the role that Twig plays in creating Drupal themes
  • Explain how Twig impacts the theming experience in Drupal
  • Locate additional resources for learning Twig
Categories
Drupal 8, 9, and 10
More information

To read a Twig template file, you'll need to recognize Twig's syntax delimiters. Twig has three syntax delimiters: one for printing out variables, another for performing actions or logic, and lastly, one for comments, also used for docblocks.

In this tutorial we'll:

  • Explore each of Twig's 3 syntax delimiters.
  • Show examples of each from Drupal's core template files.

By the end of this tutorial you should be able to recognize each of Twig's syntax delimiters and understand what the engine will do when it encounters them.

Categories
Drupal 8, 9, and 10
More information

Twig has a special syntax for accessing array keys and objects, also known in Twig as variable attributes. In this tutorial, we'll cover the period or dot (.) operator to access a variable attribute, as well as subscript or square-bracket syntax, useful for when the key of the array contains special characters, like a dash (-) or pound sign (#). We'll also look at the logic Twig uses to find the matching attribute in an array or object.

Categories
Drupal 8, 9, and 10
More information

Many of the variables that you have access to inside of a Twig template file are arrays. For example a list of values for a multi-value field, or a set of error messages generated when validating a form submission. In order to work with arrays in Twig you'll need to understand how for loops work. This is essential information for anyone creating Drupal themes.

In this tutorial we'll cover:

  • Using the for tag to iterate over an array
  • Using the loop variable inside of a for loop for additional context
Categories
Drupal 8, 9, and 10
More information

The ability to loop over an array of values in a Twig template and print out each value individually is an important skill for anyone developing themes for Drupal. Common scenarios include: loop over the values of a multiple value field; iterate through a list of links; and display error messages at the top of forms. This tutorial will provide an example of using the Twig for function to iterate over a list, or a subset of a list.

In this tutorial we'll cover how to:

  • Output values from a multi-value field in an unordered list.
  • Add first and last classes to the first and last items in a list by using the Twig loop variable.

By the end of this tutorial you should be able to print out the values of an array as individual list items using a loop in Twig.

Categories
Drupal 8, 9, and 10
More information

In Twig, you can modify variables using functions or filters. Twig has a bunch of built-in functions and filters. Drupal extends Twig to provide a few handy Drupal-specific functions and filters as well.

In this tutorial, we'll look at:

  • What are functions and filters?
  • How to use functions and filters in Twig
  • Detailed information about the Drupal-specific functions and filters and their use case
Categories
Drupal 8, 9, and 10
More information

Do you cringe at the sight of untidy whitespace or (gasp) no whitespace at all when you View Source? Learn how to tame whitespace in Twig template files in this tutorial. By the end of this lesson, you will be able to recognize how Twig controls whitespace and how you can do the same in your Drupal template files.

Categories
Drupal 8, 9, and 10
More information

In order to ensure that all user interface strings in your application can be translated using Drupal's localization system, any text you add to templates needs to use either the t filter or the {% trans %} tag. Anyone creating themes or editing template files associated with a theme or a module should know how to use these two utilities.

In this tutorial we'll look at:

  • How to use the t filter and {% trans %} tag in a Twig template
  • The differences between the two, and how to determine which one to use
  • How to translate strings assigned to variables in preprocess functions using the PHP t() function
Categories
Drupal 8, 9, and 10
More information

Theme developers often need to add or remove classes and other attributes from an HTML tag. Template files handle this with a special Attributes object that contains the attributes and their values, as well as a handful of powerful methods to help manage these attributes.

In this tutorial we’ll cover:

  • Adding/removing classes from elements in a Twig template
  • The attributes object
  • Examples of common tasks using various helper methods on the attributes object
Drupal 8, 9, and 10
More information

Before you can create a path or link to another page on your site, you'll need to know the route (unless there is already a variable available for the URL you need). Finding a route can be a tricky task unless you have the right tools. In this tutorial, we'll show how tools like Webprofiler, Drush, and Grep can be used to get route information for a page, so that you can use functions that need a route as a function parameter.

In this tutorial we'll:

  • Learn how to determine the route or path of an internal page.
Categories
Drupal 8, 9, and 10
More information

More often than not, templates in a theme share common elements: the header, footer, sidebar, or more. In Drupal, themes created with a Twig template can be decorated by another one. This template inheritance allows you to build a base "layout" template that contains all the common elements of your layout defined as blocks. A child template can extend the base layout and override any of its defined blocks. This helps prevent code duplication, and keeps your theme more organized.

This tutorial is for theme developers who want to reduce code duplication in their themes, or anyone seeking to better understand how Twig template inheritance works. We'll cover:

  • What the Twig block and extends tags do
  • An example use-case for template inheritance
  • How to extend a Twig template from another theme or module
  • How to include other Twig templates
More information

By default, individual forms in Drupal are not output using Twig template files. It's possible to associate a form with a Twig template file by creating a new theme hook, and then referencing that theme hook from the $form array that defines the form. Doing so allows theme developers to customize the layout of the elements in the form using HTML and CSS.

This is useful when you want to change the layout of the entire form. For example, putting the elements into 2 columns. If you want to change individual elements in the form, you can often do so by overriding element specific Twig template files.

In this tutorial, we'll:

  • Learn how to create a new theme hook that can be used to theme an element in a render array.
  • Associate the $form we want to theme with the new theme hook we created.
  • Create a Twig template file for the theme hook that will allow us to lay out the form elements using custom HTML.

By the end of this tutorial, you should be able to associate a Twig template file with any form in Drupal, so that you can customize its layout using HTML and CSS.

Related tutorials

Using Twig's attach_library function, you can attach asset libraries of CSS or JavaScript files. Learn more about asset libraries, or jump straight to the relevant section on attach_library in Attach a Library.

Categories
Drupal 8, 9, and 10
More information

An asset library is a bundle of CSS and/or JavaScript files that work together to provide a style and functionality for a specific component. They are frequently used to isolate the functionality and styling of a specific component, like the tabs displayed at the top of each node, into a reusable library. If you want to include CSS and/or JavaScript in your Drupal theme or module you'll need to declare an asset library that tells Drupal about the existence, and location, of those files. And then attach that library to a page, or specific element, so that it gets loaded when needed.

In this tutorial we’ll:

  • Define what an asset library is.
  • Explain why asset libraries are used to include JavaScript and CSS files.
  • Look at some example asset library definitions.

By the end of this tutorial you should be able to define what asset libraries are, and when you'll need to create one.

Categories
Drupal 8, 9, and 10
More information

New asset libraries can be defined by either modules or themes. In order to define a new asset library you need to create the requisite CSS and JavaScript files, and a new THEMENAME.libraries.yml, or MODULENAME.libraries.yml file that aggregates them together and provides metadata about the library itself and any dependencies.

In this tutorial we’ll:

  • Look at the structure of a *.libraries.yml file and demonstrate how to combine a couple of CSS and JS files together into an asset library that can be used in a theme or a module
  • Look at how one asset library can declare that it is dependent on another in order to ensure the assets from the dependency are loaded as well

By the end of this tutorial you should know how to define a new asset library in either a module or a theme.

Categories
Drupal 8, 9, and 10
More information

Once you've defined an asset library you'll need to tell Drupal when you want to add the CSS and JavaScript that it includes to the page. Ideally you'll do so in a way that allows Drupal to only add the corresponding assets on pages where they are needed.

You can attach a library to all pages, a subset of pages, or to elements in a render array. This allows you to have some assets that are global, and others that get loaded on an as-needed basis. To attach a library you'll need to know both its name and prefix, and then use one of the techniques outlined below to let Drupal know when to include it.

In this tutorial, we'll look at attaching asset libraries:

  • Globally, via your THEMENAME.info.yml file
  • Conditionally, via a preprocess function using the #attached render array property
  • Inside of a Twig template file

By the end of this tutorial you should be able to attach asset libraries in various different ways depending on your use case.

Guides

Not sure where to start? Our guides provide useful learning tracks for all skill levels.

Navigate guides

External resources

  • Twig 3.x Documentation (twig.symfony.com)
    • Official documentation for Twig. Contains a reference for tags, filters, functions, and tests, as well as information for template designers and developers looking to extend Twig with custom functionality.
  • Twig for Template Designers
    • This document describes the syntax and semantics of the template engine and will be most useful as reference to those creating Twig templates.
  • Twig in Drupal (Drupal.org)
    • Guide to community-contributed documentation on Twig as it is used in Drupal.
  • Preparing for use of Twig 2 in Drupal 9 (drupal.org)
    • The update from Drupal 8 to Drupal 9 includes updating the Twig dependency from Twig 1 to Twig 2. Unfortunately due to how composer dependencies work for Drupal 8 sites, we cannot update Drupal 8 to optionally allow Twig 2 support, even though the API is fully ready for that. So these changes can only be made currently in your Drupal 9 environment.
    • Use Upgrade Status either on the UI or via Drush to check your Twig files for deprecated syntax use.
  • Twig updated from 2.x to 3.x (Drupal.org)
    • Note especially changes to spaceless syntax and the removal of support for if inside a for clause.
  • Deprecated features in Twig 2.x (twig.symfony.com)
    • This page from Twig's official documentation lists all of the deprecated features in Twig 2.x which were removed in Twig 3.x.