phpdrupalthemesoverridingpreprocessor

Drupal main theme template file for any node


How can I switch to a different theme template file for any node that I want? I understand how to create sub-themes like node-recipes.tpl.php for a node that has a path of "recipes". But what I want to have control of the entire base template like page.tpl.php. Can I use some preprocess function in template.php for this?

Right now I have this in my template.php file:

function mythemename_preprocess_node(&$vars) {

  // template name for current node id
  $suggestions = array('node-'. $vars['nid']);

  // additional node template names based on path alias
  if (module_exists('path')) {
    // we already can have a path alias
    if (isset($vars['path'])) {
      $alias = $vars['path'];
    }else{
      // otherwise do standard check
      $alias = drupal_get_path_alias('node/'. $vars['nid']);
    }

    if ($alias != 'node/'. $vars['nid']) {
      $add_path = '';
      foreach (explode('/', $alias) as $path_part) {
        $add_path .= !empty($path_part) ? $path_part.'_' : '';
        $suggestions[] = 'node-'. $add_path;
      }
      // adding the last one (higher priority) for this path only
      // node-some-long-path-nofollow.tpl.php (not for anchestors)
      $suggestions[] = end($suggestions) .'-nofollow';
    }

    $suggestions=array_map(stripTag, $suggestions);
    //print_r($suggestions);

  }
  $vars['template_files'] = isset($vars['template_files']) ? array_merge($vars['template_files'], $suggestions) : $suggestions;
}

thanks


Solution

  • Yes,

    You can fully control the $vars['template_files'] array. I always suggest adding onto the array rather then overwriting it completely.

    I have a module that I maintain that adds a few small suggestions that I use often. http://github.com/electblake/template_suggestions/blob/master/template_suggestions.module

    You can manipulate the $vars['template_files'] array in preprocess_node, preprocess_page, etc.

    If you want to switch you page.tpl.php to another theme file do it in the preprocess_page hook...