Skip to content

Theme

Functions and templates for the user interface that themes can override.

Drupal's theme system allows a theme to have nearly complete control over the appearance of the site, which includes both the markup and the CSS used to style the markup. For this system to work, modules, instead of writing HTML markup directly, need to return "render arrays", which are structured hierarchical arrays that include the data to be rendered into HTML (or XML or another output format), and options that affect the markup. Render arrays are ultimately rendered into HTML or other output formats by recursive calls to \Drupal\Core\Render\RendererInterface::render(), traversing the depth of the render array hierarchy. At each level, the theme system is invoked to do the actual rendering. See the documentation of \Drupal\Core\Render\RendererInterface::render() and the Theme system and Render API topic for more information about render arrays and rendering.

Twig Templating Engine

Drupal uses the templating engine Twig. Twig offers developers a fast, secure, and flexible method for building templates for Drupal sites. Twig also offers substantial usability improvements over PHPTemplate, and does not require front-end developers to know PHP to build and manipulate Drupal themes.

For further information on theming in Drupal see https://www.drupal.org/docs/develop/theming-drupal

For further Twig documentation see https://twig.symfony.com/doc/3.x/templates.html

Theme Hooks

The theme system is invoked in \Drupal\Core\Render\Renderer::doRender() by calling the \Drupal\Core\Theme\ThemeManagerInterface::render() function, which operates on the concept of "theme hooks". Theme hooks define how a particular type of data should be rendered. They are registered by modules by implementing hook_theme(), which specifies the name of the hook, the input "variables" used to provide data and options, and other information. Modules implementing hook_theme() also need to provide a default implementation for each of their theme hooks in a Twig file, and they may also provide preprocessing functions. For example, the core File module defines a theme hook for a file link in \Drupal\file\Hook\FileThemeHooks::theme():

return [
  'file_link' => [
    'variables' => [
      'file' => NULL,
      'description' => NULL,
      'attributes' => [],
      'with_size' => TRUE,
    ],
    'initial preprocess' => static::class . ':preprocessFileLink',
  ],
];

Given this definition, the template file with the default implementation is file-link.html.twig, which can be found in the core/modules/file/templates directory, and the variables for rendering are the file object and a description. In addition, there is the initial preprocess method preprocessFileLink in the same class, which preprocesses the information from the input variables so that it can be rendered by the Twig template; the processed variables that the Twig template receives are documented in the header of the default Twig template file.

Theme hooks can declare a variable deprecated using the reserved 'deprecations' variable. For example:

 search_result' => [
  'variables' => [
    'result' => NULL,
    'new_result' => NULL,
    'plugin_id' => NULL,
    'deprecations' => [
      'result' => "'result' is deprecated in drupal:X.0.0 and is removed from drupal:Y.0.0. Use 'new_result' instead. See https://www.example.com."
    ]
  ],
],

Template engines should trigger a deprecation error if a deprecated variable is used in a template.

Overriding Theme Hooks

Themes may register new theme hooks within a hook_theme() implementation, but it is more common for themes to override default implementations provided by modules than to register entirely new theme hooks. Themes can override a default implementation by creating a template file with the same name as the default implementation; for example, to override the display of file links, a theme would add a file called file-link.html.twig to its templates directory. A good starting point for doing this is normally to copy the default implementation template, and then modifying it as desired.

Preprocessing for Template Files

Several functions are called before the template file is invoked to modify the variables that are passed to the template. These make up the "preprocessing" phase, and are executed (if they exist), in the following order (note that in the following list, HOOK indicates the hook being called or a less specific hook. For example, if '#theme' => 'node__article' is called, hook is node__article and node. MODULE indicates a module name, THEME indicates a theme name, and ENGINE indicates a theme engine name). Modules, themes, and theme engines can provide these functions to modify how the data is preprocessed, before it is passed to the theme template:

  • ThemeManager::addDefaultTemplateVariables(&$variables): Creates a default set of variables for all theme hooks. Provided by Drupal Core.
  • initial preprocess: A callback set on the theme hook definition, to set up default variables. Supports services with the service:method syntax, see \Drupal\Core\Utility\CallableResolver and hook_theme().
  • MODULE_preprocess(&$variables, $hook): hook_preprocess() is invoked on all implementing modules.
  • MODULE_preprocess_HOOK(&$variables): hook_preprocess_HOOK() is invoked on all implementing modules, so that modules that didn't define the theme hook can alter the variables.
  • ENGINE_engine_preprocess(&$variables, $hook): Allows the theme engine to set necessary variables for all theme hooks with template implementations.
  • ENGINE_engine_preprocess_HOOK(&$variables): Allows the theme engine to set necessary variables for the particular theme hook.
  • THEME_preprocess(&$variables, $hook): Allows the theme to set necessary variables for all theme hooks with template implementations.
  • THEME_preprocess_HOOK(&$variables): Allows the theme to set necessary variables specific to the particular theme hook.

Theme hook suggestions

In some cases, instead of calling the base theme hook implementation (either the default provided by the module that defined the hook, or the override provided by the theme), the theme system will instead look for "suggestions" of other hook names to look for. Suggestions can be specified in several ways:

  • In a render array, the '#theme' property (which gives the name of the hook to use) can be an array of theme hook names instead of a single hook name. In this case, the render system will look first for the highest-priority hook name, and if no implementation is found, look for the second, and so on. Note that the highest-priority suggestion is at the end of the array.
  • In a render array, the '#theme' property can be set to the name of a hook with a '__SUGGESTION' suffix. For example, if an 'article' content type exists, the hook 'node__article' can be given. In this case, the render system will look for theme templates called node--article.html.twig, which would only be used for rendering article nodes, and if this template is not found, it will fall back to using the base node.html.twig template. This type of suggestion can also be combined with providing an array of theme hook names as described above.
  • A module can implement hook_theme_suggestions_HOOK(). This allows the module that defines the theme template to dynamically return an array containing specific theme hook names (presumably with '__' suffixes as defined above) to use as suggestions. For example, the Node module implements hook_theme_suggestions_node() to suggest node__BUNDLE as the theme hook for node items, where BUNDLE is the machine name of the particular node type (such as article or page).

For further information on overriding theme hooks see https://www.drupal.org/node/2186401

Altering theme hook suggestions

Modules can also alter the theme suggestions provided using the mechanisms of the previous section. There are two hooks for this: the theme-hook-specific hook_theme_suggestions_HOOK_alter() and the generic hook_theme_suggestions_alter(). These hooks get the current list of suggestions as input, and can change this array (adding suggestions and removing them).

Assets

We can distinguish between three types of assets:

  • Unconditional page-level assets (loaded on all pages where the theme is in use): these are defined in the theme's *.info.yml file.
  • Conditional page-level assets (loaded on all pages where the theme is in use and a certain condition is met): these are attached in hook_page_attachments_alter(), e.g.:
function THEME_page_attachments_alter(array &$page) {
  if ($some_condition) {
    $page['#attached']['library'][] = 'my_theme/something';
  }
}
  • Template-specific assets (loaded on all pages where a specific template is in use): these can be added by in preprocessing functions, using
$variables['#attached'];

, e.g.:

function THEME_preprocess_menu_local_action(array &$variables) {
  // We require touch events detection for button styling.
  $variables['#attached']['library'][] = 'core/drupal.touchevents-test';
}

Front Matter

Twig has been extended in Drupal to provide an easy way to parse front matter from template files. See \Drupal\Component\FrontMatter\FrontMatter for more information:

$metadata = \Drupal::service('twig')->getTemplateMetadata('/path/to/template.html.twig');

Note: all front matter is stripped from templates prior to rendering.

Theme Update functions

Themes support post updates in order to install module dependencies that have been added to the THEME.info.yml after the theme has been installed. Additionally, if a theme has changed its configuration schema, post updates can fix theme settings configuration. See hook_post_update_NAME for more information about post updates.

See also

Hooks

Callbacks

Render API overview