基于URL别名使用不同的drupal页面模板

可以在你的template.php文件中修改一个模板的“模板建议”("template suggestions")列表。下面的代码片断,将根据当前页面的URL别名来添加页面模板建议。这样你就可以为'music'路径或者目录下面的页面定义一个page-music.tpl.php模板文件了。

Drupal 5版本:

<?php
function _phptemplate_variables($hook, $vars = array()) {
  switch ($hook) {
    case 'page':
   
      // Add page template suggestions based on the aliased path.
      // For instance, if the current page has an alias of about/history/early,
      // we'll have templates of:
      // page-about-history-early.tpl.php
      // page-about-history.tpl.php
      // page-about.tpl.php
      // Whichever is found first is the one that will be used.
      if (module_exists('path')) {
        $alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));
        if ($alias != $_GET['q']) {
          $suggestions = array();
          $template_filename = 'page';
          foreach (explode('/', $alias) as $path_part) {
            $template_filename = $template_filename . '-' . $path_part;
            $suggestions[] = $template_filename;
          }
        }
        $vars['template_files'] = $suggestions;
      }
      break;
  }
 
  return $vars;
}
?>





Drupal 6版本:

<?php
function phptemplate_preprocess_page(&$vars) {
  if (module_exists('path')) {
    $alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));
    if ($alias != $_GET['q']) {
      $suggestions = array();
      $template_filename = 'page';
      foreach (explode('/', $alias) as $path_part) {
        $template_filename = $template_filename . '-' . $path_part;
        $suggestions[] = $template_filename;
      }
    }
    $vars['template_files'] = $suggestions;
  }
}
?>

 

变通

下面的是这个方法的一些变通应用。

在一个页面模板中仅修改一个CSS类。适用于那些不需要创建一个新的模板,仅需要修改CSS的情况。

<?php
    if (module_exists('path')) {
        $alias = drupal_get_path_alias($_GET['q']);
        $class = explode('/', $alias);
        print '<div class="page page-'.$class[0].'">';
    }
?>

对特定节点类型的修改限制:

<?php
      // (...)
      if(arg(0)=='node') {
          $vars['template_files'] = 'page_' . $vars['node']->type;
     }
     // (...)
?>

 

 相关链接: http://drupal.org/node/139766 , Think in Drupal

Drupal版本: