预先说明:如果您的实际条件取决于请求 URL,如您的示例所示,那么我同意 Terry Seidlers 的评论,即您应该*_preprocess_page()
在自定义模块的实现中或在您的主题中执行此操作template.php
。
更通用的选项:
*_preprocess_page()
AFAIK,这在开箱即用的功能之外是不可能的。但是,您可以使用辅助函数轻松添加此功能:
/**
* 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_preprocess_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));
}
我通常在自定义模块中执行此操作,但您可以在主题 template.php 文件中执行相同操作。
有了这个,您几乎可以在任何地方执行以下操作,例如在块组装期间:
if ($someCondition) {
yourModule_add_body_class('someBodyClass');
}