如何在Drupal6的块中添加带有php的body类?
我在Drupal6中有一个包含php代码的块,我想在它的主体中添加一个特定的类,但是我如何才能做到这一点呢 甚至可以在预处理函数之外执行此操作吗 显示以下PHP代码是否返回TRUE(PHP模式,仅限专家)如何在Drupal6的块中添加带有php的body类?,php,css,drupal,drupal-6,drupal-blocks,Php,Css,Drupal,Drupal 6,Drupal Blocks,我在Drupal6中有一个包含php代码的块,我想在它的主体中添加一个特定的类,但是我如何才能做到这一点呢 甚至可以在预处理函数之外执行此操作吗 显示以下PHP代码是否返回TRUE(PHP模式,仅限专家) 预先评论:如果您的实际情况取决于请求URL,如您的示例所示,那么我同意Terry Seidler的意见,即您应该在自定义模块中的*\u preprocess\u page()实现中或在主题模板.php中执行此操作 更通用的选项: 好的,这在一个现成的*\u preprocess\u page(
预先评论:如果您的实际情况取决于请求URL,如您的示例所示,那么我同意Terry Seidler的意见,即您应该在自定义模块中的
*\u preprocess\u page()
实现中或在主题模板.php
中执行此操作
更通用的选项:
好的,这在一个现成的*\u preprocess\u page()
函数之外是不可能的。但是,您可以通过助手函数轻松添加此功能:
/**
* Add a class to the body element (preventing duplicates)
* NOTE: This function works similar to drupal_add_css/js, in that it 'collects' classes within a static cache,
* adding them to the page template variables later on via yourModule_preprocess_page().
* This implies that one can not reliably use it to add body classes from within other
* preprocess_page implementations, as they might get called later in the preprocessing!
*
* @param string $class
* The class to add.
* @return array
* The classes from the static cache added so far.
*/
function yourModule_add_body_class($class = NULL) {
static $classes;
if (!isset($classes)) {
$classes = array();
}
if (isset($class) && !in_array($class, $classes)) {
$classes[] = $class;
}
return $classes;
}
这允许您在页面周期的任何地方从PHP代码中“收集”任意主体类,只要在最终页面预处理之前调用它即可。这些类存储在静态数组中,实际添加到输出中的是yourModule\u preprocess\u page()
实现:
/**
* Implementation of preprocess_page()
*
* @param array $variables
*/
function yourModule_preprocess_page(&$variables) {
// Add additional body classes, preventing duplicates
$existing_classes = explode(' ', $variables['body_classes']);
$combined_classes = array_merge($existing_classes, yourModule_add_body_class());
$variables['body_classes'] = implode(' ', array_unique($combined_classes));
}
我通常在自定义模块中执行此操作,但您也可以在themes template.php文件中执行相同的操作
在适当的位置,您几乎可以在任何地方执行以下操作,例如在块装配期间:
if ($someCondition) {
yourModule_add_body_class('someBodyClass');
}
使用jquery jquery('body').addClass('test');我当然不想用jquery这样做……为什么要在块中而不是模板预处理页面中这样做?()
if ($someCondition) {
yourModule_add_body_class('someBodyClass');
}