我在 drupal 6 中有一个带有 php 代码的 block ,我想将某个类添加到主体中,但如何实现这一点?
是否可以在预处理函数之外执行此操作?
Show if the following PHP code returns TRUE (PHP-mode, experts only).
<?php
$url = request_uri();
if (strpos($url, "somestring"))
{
$vars['body_classes'] .= ' someclass';
}
elseif ( arg(0) != 'node' || !is_numeric(arg(1)))
{
return FALSE;
}
$temp_node = node_load(arg(1));
$url = request_uri();
if ( $temp_node->type == 'type' || strpos($url, "somestring"))
{
return TRUE;
}
?>
最佳答案
预先说明:如果您的实际情况取决于请求 URL(如您的示例所示),那么我同意 Terry Seidlers 的评论,即您应该在 *_preprocess_page( )
在自定义模块或主题 template.php
中实现。
更通用的选项:
据我所知,这是不可能从开箱即用的 *_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));
}
我通常在自定义模块中执行此操作,但您也可以在主题 template.php 文件中执行相同的操作。
有了这个,您几乎可以在任何地方执行以下操作,例如在 block 组装期间:
if ($someCondition) {
yourModule_add_body_class('someBodyClass');
}
关于php - 如何在 drupal 6 的 block 内添加带有 php 的主体类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13859781/