2

I'm trying to switch the node template file based on a variable, in drupal 6 you could simply set $vars['template_file'] = 'node-whatever'; from with the preprocess_node() and name the new node template file node-whatever.tpl.php. I drupal 7 this is gone. I looked through the docs and it appears that in Drupal 7 its $vars['theme_hook_suggestion'][] = 'node--whatever'; but this is not working for me. Am I doing something wrong? is there a naming convention that I'm missing? The documentation is a little confusing

2 Answers 2

6

Indeed, in D7 the template suggestions are an array of suggestions, in the order of importance. You've got 99% of it, but your dashes need to be underscores. Try:

function THEME_preprocess_page() {
  $vars['theme_hook_suggestions'][] = 'page__whatever';
}

function THEME_preprocess_node() {
  $vars['theme_hook_suggestions'][] = 'node__whatever';
}

Why underscores instead of hyphens? From the Drupal API docs:

  // Hyphens (-) and underscores (_) play a special role in theme suggestions.
  // Theme suggestions should only contain underscores, because within
  // drupal_find_theme_templates(), underscores are converted to hyphens to
  // match template file names, and then converted back to underscores to match
  // pre-processing and other function names. So if your theme suggestion
  // contains a hyphen, it will end up as an underscore after this conversion,
  // and your function names won't be recognized.
2
  • 1
    also I had $vars['theme_hook_suggestion'] rather than $vars['theme_hook_suggestions'] (plural) ... stupid
    – user379468
    Commented Feb 16, 2012 at 18:14
  • 1
    Thank you so much for pointing the underscore thing out. I spent over an hour trying to figure out why my template was not discovered - and it contained hyphens.
    – naxoc
    Commented Apr 12, 2012 at 8:06
0

Some Drupal 7 example where you're loading different TPL template based on taxonomy term wich Page has (field_page_category):

/**
 * Override or insert variables into the node templates.
 *
 */
function phptemplate_preprocess_node(&$vars, $hook) {
  $node = $vars['node'];
  switch($node->type) {
    case 'page':
      $tid = $node->field_page_category[LANGUAGE_NONE][0]['taxonomy_term']->tid;
      $parents = taxonomy_get_parents_all($tid);
      foreach ($parents as $tid => $term) {
        $category = ereg_replace('[[:space:]]', '-', $term->name);
        // Suggest a theme name, see: https://drupal.org/node/1089656
        $vars['theme_hook_suggestions'][] = 'node__page__'. strtolower($category);
      }
    break;
  } // end: switch
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.