Drupal Theme Hook Suggestions

Theme hook enables any module or theme to provide suggestions for alternative theme feature or template name suggestions and reorder or remove suggestions.

Drupal 7:

<?php
/**
* Implements hook_preprocess_HOOK() for node templates.
*/
function MYTHEME_preprocess_node(&$variables) {
  $variables['theme_hook_suggestions'][] = 'node__' . 'first';
  $variables['theme_hook_suggestions'][] = 'node__' . 'second';
}

Drupal 8:

<?php
/**
* Implements hook_theme_suggestions_HOOK_alter() for node templates.
*/
function MYTHEME_theme_suggestions_node_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'node__' . 'first';
  $suggestions[] = 'node__' . 'second';
}

 

hook_preprocess for suggestions

To add a template file suggestion for the page hook, you would implement hook_theme_suggestions_page_alter().

/* for $suggestions[] = 'node__' . 'first'; */
function hook_preprocess_node__first(&$variables);

/* for $suggestions[] = 'node__' . 'second'; */
function hook_preprocess_node__second(&$variables);

 

Example Drupal8:

/**
 * Implements hook_theme_suggestions_alter
 *
 * {@inheritdoc}
 */
function simplelogin_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if ($hook == 'page') {
    $path = \Drupal::service('path.current')->getPath(); 
    $current_user = \Drupal::currentUser();  // Whether the current user is anonymous or authenticated
    if (!$current_user->id()) {
       $suggestions[] = 'page__simplelogin';
    }
  }
}

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
8 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.