Skip to content

Instantly share code, notes, and snippets.

@rpayanm
Last active January 16, 2020 13:28
Show Gist options
  • Save rpayanm/d1c59120edf837ae7f6138f0ff1810da to your computer and use it in GitHub Desktop.
Save rpayanm/d1c59120edf837ae7f6138f0ff1810da to your computer and use it in GitHub Desktop.

Alter theme hook suggestions

Add your own theme hook suggestions

Modules and themes can alter the list of theme hook suggestions using one of these two hooks. They both function the same but vary in specificity:

  • hook_theme_suggestions_alter(array &$suggestions, array $variables, $hook)
  • hook_theme_suggestions_HOOK_alter(array &$suggestions, array $variables)

Example:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  $logged_in = \Drupal::currentUser()->isAuthenticated();
  if ($logged_in) {
    $suggestions[] = 'node__' . 'authenticated';
  }
}

Same as below:

/**
 * Implements hook_theme_suggestions_alter().
 */
function MYTHEME_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if ($hook == 'node') {
    $logged_in = \Drupal::currentUser()->isAuthenticated();
    if ($logged_in) {
      $suggestions[] = 'node__' . 'authenticated';
    }
  }
}

Remove or reorder theme hook suggestions

Using hook_theme_suggestions_HOOK_alter(), a module or theme can also remove a suggestion from the list or reorder the list completely. You simply need to make modifications to the $suggestions array passed to the function. Suggestions are used in the order they appear in the array, so if you want to change priorty simply shuffle the array. Both cases are rare, but good to know about.

function hook_theme_suggestions_HOOK allows modules to provide alternative theme function or template name suggestions.

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function hook_theme_suggestions_HOOK(array $variables) {
  $suggestions = [];
  $suggestions[] = 'node__' . $variables['elements']['#langcode'];
  return $suggestions;
}

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_theme_suggestions_HOOK/8.8.x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment