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に依存している場合は*_preprocess_page()、カスタムモジュールの実装内またはテーマ内でこれを行う必要があるというTerrySeidlerstemplate.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 に答える