function hook_preprocess

hook_preprocess(&$variables, $hook)

Preprocess theme variables for templates.

This hook allows modules to preprocess theme variables for theme templates. It is called for all theme hooks implemented as templates, but not for theme hooks implemented as functions. hook_preprocess_HOOK() can be used to preprocess variables for a specific theme hook, whether implemented as a template or function.

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

Hooks
Define functions that alter the behavior of Drupal core.

File

core/lib/Drupal/Core/Render/theme.api.php, line 557
Hooks and documentation related to the theme and render system.

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 function 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';
    }
  }
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook_preprocess/8.1.x