2

我在 drupal 6 中有一个带有 php 代码的块,我想将某个类添加到正文中,但是我该如何实现呢?

甚至可以在预处理功能之外执行此操作吗?

显示以下 PHP 代码是否返回 TRUE(PHP 模式,仅限专家)。

<?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;
}
?>
4

1 回答 1

3

预先说明:如果您的实际条件取决于请求 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');
}
于 2012-12-14T19:07:25.613 回答