Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท Themes and Twig

Preprocess Functions and Libraries

Prepare data for Twig with hook_preprocess functions, attach libraries per template, add classes and variables, and learn how the preprocess chain runs, with a runnable stand-in.

Twig templates should only present data. When a template needs something that is not already a variable, such as a formatted date, a computed class or a flag from another field, you prepare it in a preprocess function in your theme's .theme file. Drupal calls preprocess functions just before it renders a template, giving you the chance to add, change or remove variables.

The Drupal and PHP code is read-only; the TryIt blocks are JavaScript stand-ins that follow the same sequence (every registered function gets the variables array, in order).

The naming pattern

A preprocess function is named THEME_preprocess_HOOK, where THEME is your theme's machine name and HOOK the theme hook (node, page, block, field, views_view, html...). Variables arrive by reference as $variables:

PHP
<?php

/**
 * Implements hook_preprocess_node().
 */
function sunrise_preprocess_node(array &$variables): void {
  /** @var \Drupal\node\NodeInterface $node */
  $node = $variables['node'];

  $variables['reading_time'] = 0;
  if ($node->hasField('body') && !$node->get('body')->isEmpty()) {
    $words = str_word_count(strip_tags($node->get('body')->value));
    $variables['reading_time'] = max(1, (int) ceil($words / 200));
  }

  if ($node->isSticky()) {
    $variables['attributes']['class'][] = 'is-featured';
  }
}

In node.html.twig you now print {{ reading_time }} min read. Because the node type is known you can also target it exactly: sunrise_preprocess_node__article() runs only for Article nodes. Modules can add preprocess functions too, and Drupal runs them in a defined order: module functions first, then base theme, then your theme.

Where is the data?

A render array contains # properties and children. In preprocess you mostly read:

  • $variables['node'], $variables['user'], $variables['elements']: the entity or its render elements.
  • $variables['content']: the field render arrays that Twig prints.
  • $variables['attributes']: the HTML attributes; add classes with $variables['attributes']['class'][] = 'x'.
  • $variables['view_mode']: full, teaser and so on.

Use $node->get('field_name')->value, ->target_id for references, ->entity to load a referenced entity, and ->isEmpty() before using anything.

Node.js Stand-in: preprocess functions run in order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Attaching libraries

Declare the library once in sunrise.libraries.yml, then attach it where it is needed:

HTML
{{ attach_library('sunrise/gallery') }}
<div class="gallery">...</div>

or in preprocess:

PHP
function sunrise_preprocess_node__gallery(array &$variables): void {
  $variables['#attached']['library'][] = 'sunrise/gallery';
}

The gallery CSS and JavaScript now load only on pages that show a gallery. Smaller pages and fewer requests are one of the biggest wins a theme can give a site. For values that JavaScript needs, pass them through settings:

PHP
$variables['#attached']['drupalSettings']['sunrise']['gallery'] = ['speed' => 4000];

and read drupalSettings.sunrise.gallery.speed inside a behavior.

Page-level and html-level preprocess

hook_preprocess_html lets you add body classes, for example per route or role:

PHP
function sunrise_preprocess_html(array &$variables): void {
  $route = \Drupal::routeMatch()->getRouteName();
  $variables['attributes']['class'][] = 'route-' . \Drupal\Component\Utility\Html::getClass($route);
  $variables['#cache']['contexts'][] = 'route';
}

Note the cache context: if output depends on the route, say so. See caching and cache tags.

Responsive images and other presentation helpers

Images are best handled by configuration: define image styles (resize, crop) and a responsive image style that maps breakpoints to styles. Then the field formatter outputs <picture> with srcset. Your theme supplies a sunrise.breakpoints.yml:

YAML
sunrise.mobile:
  label: Mobile
  mediaQuery: ''
  weight: 0
  multipliers: [1x, 2x]
sunrise.wide:
  label: Wide
  mediaQuery: 'all and (min-width: 1024px)'
  weight: 1
  multipliers: [1x, 2x]

Keep it clean

A useful rule: if a variable is about how something looks (a class, an icon name), compute it in preprocess; if it is about what the site does (loading data, permissions), a module or service should do it and the theme only asks. The next stand-in shows a small helper that maps a content type to a CSS class, the kind of logic that belongs here.

Node.js Stand-in: building safe CSS classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Common mistakes

  • Doing database queries in a preprocess function that runs for every row of a list. Prefer a view or cached data.
  • Forgetting $variables is passed by reference (array &$variables).
  • Naming the function after the folder instead of the theme machine name.
  • Adding attributes in preprocess and not printing {{ attributes }} in the template.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the correct name of a preprocess function for blocks in the theme sunrise?

    The pattern is THEME_preprocess_HOOK.
  2. 2. Why attach a library from a template instead of globally?

    Targeted libraries keep other pages lighter.
  3. 3. How do you pass a value to JavaScript?

    drupalSettings is serialized into the page and read in JavaScript as drupalSettings.
  4. 4. In what order do preprocess functions for one hook run?

    The theme closest to the output gets the last word.

Summary

  • THEME_preprocess_HOOK(array &$variables) prepares data for templates.
  • Modules run first, the active theme last; add variables, classes and libraries here.
  • attach_library() or #attached loads assets only where needed.
  • Keep business logic in modules; presentation helpers in the theme.
  • Declare cache contexts when output varies by route or user.

Next: Custom Module Basics