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

Last updated July 27, 2016

Preprocess functions are specially named functions that can be used to add new variables to a Twig template file.

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:

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