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