Theming

Add Variables to a Template File for Drupal 8, 9, and 10

Preprocess functions are specially-named functions that can be used to add new variables to a Twig template file. They are commonly used by themes to add new variables based on custom PHP logic and simplify accessing the data contained in complex entity structures. For example: adding a variable to all node.html.twig template files that contains the combined content a couple of specific fields under a meaningful name like {{ call_to_action }}. Modules use preprocess functions to expose the dynamic data they manage to Twig template files, or to alter data provided by another module based on custom logic.

In this tutorial we'll learn how to:

  • Use PHP to perform some complex logic in our theme.
  • Store the resulting calculation in a variable.
  • Make that variable available to a Twig template file.

Example use cases for adding variables with preprocess functions include:

  • Anytime calculating the value to output in a template requires logic more complex than an if/else statement.
  • Anytime the desired value requires additional string manipulation beyond what can be easily accomplished using an existing Twig filter or function.

By the end of this tutorial you should be able to expose new variables to a Twig template file by defining a preprocess function in either a module or a theme.

Theming Drupal Sites