前期備註:如果你的實際情況取決於請求URL,因爲你的例子顯示,然後我跟特里Seidlers評論同意你剛纔應該在自定義做一個*_preprocess_page()
實現中模塊或在您的主題template.php
。
更通用的選項:
AFAIK,這是不是從一個*_preprocess_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_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));
}
我通常做這從一個自定義模塊內,但你可以一個主題模板中做同樣的。 PHP文件。
使用此功能,您幾乎可以在任何地方執行以下操作,例如:塊組裝時:
if ($someCondition) {
yourModule_add_body_class('someBodyClass');
}
使用jquery jQuery('body')。addClass('test'); – softsdev
我當然不想用jQuery來做這件事... – Alex
爲什麼你想在一個塊中做這個,而不是template_preprocess_page? (http://api.drupal.org/api/drupal/includes!theme.inc/function/template_preprocess_page/6) –