You are here

如何为每个drupal页面生成<body> class/id属性

g089h515r806 的头像
Submitted by g089h515r806 on 星期四, 2008-09-11 07:51

这个代码将为你drupal站点上的每个页面的<body>标签生成一个类(class)和id。

在你主题的页面模板文件(page.tpl.php)中,将已存在的<body>标签替换为下面的代码:

<body<?php print phptemplate_body_attributes($is_front, $layout); ?>>

      

并在你主题的template.php文件中添加下面的代码:

 

/**

* Sets the body tag class and id attributes.

*

* From the Theme Developer's Guide, http://drupal.org/node/32077

*

* @param $is_front

*   boolean Whether or not the current page is the front page.

* @param $layout

*   string Which sidebars are being displayed.

* @return

*   string The rendered id and class attributes.

*/

function phptemplate_body_attributes($is_front = false, $layout = 'none') {

 

  if ($is_front) {

    $body_id = $body_class = 'homepage';

  }

  else {

    // Remove base path and any query string.

    global $base_path;

    list(,$path) = explode($base_path, $_SERVER['REQUEST_URI'], 2);

    list($path,) = explode('?', $path, 2);

    $path = rtrim($path, '/');

    // Construct the id name from the path, replacing slashes with dashes.

    $body_id = str_replace('/', '-', $path);

    // Construct the class name from the first part of the path only.

    list($body_class,) = explode('/', $path, 2);

  }

  $body_id = 'page-'. $body_id;

  $body_class = 'section-'. $body_class;

 

  // Use the same sidebar classes as Garland.

  $sidebar_class = ($layout == 'both') ? 'sidebars' : "sidebar-$layout";

 

  return " id=\"$body_id\" class=\"$body_class $sidebar_class\"";

}

 

注意:这里你需要启用简洁url,才能正常使用。

 

使用例子:

使用了这段代码后,当你访问news/archive/2007页面时,你将看到下面的<body>属性:

<body id="page-news-archive-2007" class="section-news sidebar-left">

现在你要做的就是为整个站点的新闻栏目创建一套新的CSS规则:

.content { background-image: url("background.png"); }

.section-news .content { background-image: url("news.png"); }

 

如果你启用了路径别名模块的话,并且花了功夫为你的页面创建了多层级的路径,这样你就很容易将站点分为做个栏目,然后为每个栏目使用一个完全不同的布局(背景图片,颜色,宽度等等)。

 相关联接: http://drupal.org/node/32077 ,  Think in Drupal

Drupal版本: