Drupal main theme template file for any node

2019-08-07 20:13发布

问题:

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

回答1:

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...



回答2:

I'm using this function to create template suggestions that works for me now. Thanks for the suggestions everyone.

/**
 * Override or insert PHPTemplate variables into the templates.
 * These are the main outer templates such as page.tpl.php 
 */
function phptemplate_preprocess_page(&$vars) {

    $alias = drupal_get_path_alias($_GET['q']);
    if ($alias != $_GET['q']) {
        $template_filename = 'page';
        foreach (explode('/', $alias) as $path_part) {
            $template_filename = $template_filename . '-' . $path_part;
            $vars['template_files'][] = $template_filename;
        }
    }
    //----  

//print_r(arg()); 

/*  print '<pre>';
  print_r($vars);
  print '</pre>';*/

  //dpm($vars);
  //print_r($vars['template_files']);

}