function hook_preprocess

Same name and namespace in other branches
  1. 7.x modules/system/theme.api.php \hook_preprocess()
  2. 8.9.x core/lib/Drupal/Core/Render/theme.api.php \hook_preprocess()
  3. 10 core/lib/Drupal/Core/Render/theme.api.php \hook_preprocess()
  4. 11.x core/lib/Drupal/Core/Render/theme.api.php \hook_preprocess()

Preprocess theme variables for templates.

This hook allows modules to preprocess theme variables for theme templates. It is called for all theme hooks. hook_preprocess_HOOK() can be used to preprocess variables for a specific theme hook.

For more detailed information, see the Theme system overview topic.

Parameters

$variables: The variables array (modify in place).

$hook: The name of the theme hook.

Related topics

8 functions implement hook_preprocess()

Note: the procedural functions in this list are found by pattern matching, so the list may include some functions that are not actually implementations of this hook.

CommonTestThemeHooks::preprocess in core/modules/system/tests/modules/common_test/src/Hook/CommonTestThemeHooks.php
Implements hook_preprocess().
common_test_preprocess in core/modules/system/tests/modules/common_test/common_test.module
Implements MODULE_preprocess().
ContextualThemeHooks::preprocess in core/modules/contextual/src/Hook/ContextualThemeHooks.php
Implements hook_preprocess().
contextual_preprocess in core/modules/contextual/contextual.module
Implements hook_preprocess().
ModuleTestOopPreprocessThemeHooks::rootPreprocess in core/modules/system/tests/modules/module_test_oop_preprocess/src/Hook/ModuleTestOopPreprocessThemeHooks.php
#[Hook('preprocess')]

... See full list

File

core/lib/Drupal/Core/Render/theme.api.php, line 541

Code

function hook_preprocess(&$variables, $hook) {
    static $hooks;
    // Add contextual links to the variables, if the user has permission.
    if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
        return;
    }
    if (!isset($hooks)) {
        $hooks = theme_get_registry();
    }
    // Determine the primary theme hook argument.
    if (isset($hooks[$hook]['variables'])) {
        $keys = array_keys($hooks[$hook]['variables']);
        $key = $keys[0];
    }
    else {
        $key = $hooks[$hook]['render element'];
    }
    if (isset($variables[$key])) {
        $element = $variables[$key];
    }
    if (isset($element) && is_array($element) && !empty($element['#contextual_links'])) {
        $variables['title_suffix']['contextual_links'] = contextual_links_view($element);
        if (!empty($variables['title_suffix']['contextual_links'])) {
            $variables['attributes']['class'][] = 'contextual-links-region';
        }
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.