Drupal API

hook_theme

Все известные Друпал-разработчики оставили свой след в переводах документации. Оставь и ты! Это очень просто, первый шаг — регистрация.

developer/hooks/core.php, строка 1802

Версии
6
hook_theme($existing, $type, $theme, $path)

Регистрирует темизации модуля или темы.

Модули и темы, реализующие этот хук, возвращают массив ассоциативных массивов. Ключ каждого из под-массивов является внутренним именем хука, а сам под-массив содержит информацию о хуке. Каждый под-массив может содержать следующие пункты:

  • 'arguments': (обязательный ключ) Массив параметров данного хука темизации. Он позволяет слою темы правильно использовать файлы шаблонов. Каждый параметр описывается как пара ключ-значение, где ключом является имя параметра, а значением — значение этого параметра по умолчанию (оно будет использовано, если этот параметр не будет передан функции theme()). Порядок параметров в описании должен совпадать с порядком, в котором они будут передаваться в theme().
  • 'file': Имя файла, в котором находится реализация данного хука темизации. Этот файл будет включен перед отображением темы, чтобы подгрузить необходимую функцию для слоя темы; благодаря этому функции темизации можно выносить в отдельный файл и подгружать только при необходимости.
  • 'path': Путь к include-файлу, указаному в ключе 'file'. В большинстве случаев 'path' можно не указывать, и файл будет взят из одной директории с модулем/темой. Но если файл находится в другом месте, необходимо это указать. Путь должен быть относительным, начиная с корневой директории Друпала.
  • 'template': Если задан, этот ключ указывает на то, что данная темизация реализуется с помощью шаблона, а также задает само имя шаблона (без расширения .tpl.php). Расширение добавит стандартный движок тем Друпала (PHPTemplate). Если задан также параметр 'path', то шаблон будет загружен из заданной этим параметром директории.
  • 'function': Если этот ключ задан, он будет использован в качестве имени функции, реализующей данный хук темизации. Если не задан ни один из ключей 'file' и 'function', то считается, что реализация хука находится в функции с именем по умолчанию. Для модуля, зарегистрировавшего хук темизации 'node', функция по умолчанию называется 'theme_node'. Для темы chameleon, зарегистрировавшей хук 'node', функция называется 'chameleon_node'.
  • 'pattern': Шаблон регулярного выражения, совпадения с которым будут использовать эту реализацию темизаций с динамическими именами. Считается правильным использовать __ для отделения динамической части имени темы. Например, чтобы темизировать форумы индивидуально, шаблон может быть: 'forum__'. Тогда, когда форум темизируется вызывается: theme(array('forum__'. $tid, 'forum'), $forum).
  • 'preprocess functions': Массив функций для предварительной обработки параметров хука. Ordinarily this won't be used; it's automatically filled in. By default, for a module this will be filled in as template_preprocess_HOOK. For a theme this will be filled in as phptemplate_preprocess and phptemplate_preprocess_HOOK as well as themename_preprocess and themename_preprocess_HOOK.
  • 'override preprocess functions': Set to TRUE when a theme does NOT want the standard preprocess functions to run. This can be used to give a theme FULL control over how variables are set. For example, if a theme wants total control over how certain variables in the page.tpl.php are set, this can be set to true. Please keep in mind that when this is used by a theme, that theme becomes responsible for making sure necessary variables are set.
  • 'type': (automatically derived) Where the theme hook is defined: 'module', 'theme_engine', or 'theme'.
  • 'theme path': (automatically derived) The directory path of the theme or module, so that it doesn't need to be looked up.
  • 'theme paths': (automatically derived) An array of template suggestions where .tpl.php files related to this theme hook may be found.

The following parameters are all optional.

Параметры

$existing An array of existing implementations that may be used for override purposes. This is primarily useful for themes that may wish to examine existing implementations to extract data (such as arguments) so that it may properly register its own, higher priority implementations.

$type What 'type' is being processed. This is primarily useful so that themes tell if they are the actual theme being called or a parent theme. May be one of:

  • module: A module is being checked for theme implementations.
  • base_theme_engine: A theme engine is being checked for a theme which is a parent of the actual theme being used.
  • theme_engine: A theme engine is being checked for the actual theme being used.
  • base_theme: A base theme is being checked for theme implementations.
  • theme: The actual theme in use is being checked.
$theme The actual name of theme that is being being checked (mostly only useful for theme engine).

$path The directory path of the theme or module, so that it doesn't need to be looked up.

Возвращаемое значение

Массив с ключами хуков темы.

Связанные темы

▸ 1 функция вызывает hook_theme()

▾ 1 функция вызывает hook_theme()

_theme_build_registry in includes/theme.inc
Rebuild the hook theme_registry cache.

Код

<?php
function hook_theme($existing, $type, $theme, $path) {
  return array(
    'forum_display' => array(
      'arguments' => array('forums' => NULL, 'topics' => NULL, 'parents' => NULL, 'tid' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
    ),
    'forum_list' => array(
      'arguments' => array('forums' => NULL, 'parents' => NULL, 'tid' => NULL),
    ),
    'forum_topic_list' => array(
      'arguments' => array('tid' => NULL, 'topics' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
    ),
    'forum_icon' => array(
      'arguments' => array('new_posts' => NULL, 'num_posts' => 0, 'comment_mode' => 0, 'sticky' => 0),
    ),
    'forum_topic_navigation' => array(
      'arguments' => array('node' => NULL),
    ),
  );
}
?>

Пользовательские комментарии

Альтернатива hook_theme() для Drupal 5: http://drupal.org/node/337327

Краткий пример:

   // You  can pass any number of arguments to theme()
   $output =  theme('ИМЯ_МОДУЛЯ_ИМЯ_ФУНКЦИИ', $arg1);
...
function  theme_ИМЯ_МОДУЛЯ_ИМЯ_ФУНКЦИИ($text) {
   return '<span class="some-class">' . $text . '</text>';
}

Подробнее про использование темизации можно прочитать в статье Using the theme layer (Drupal 6.x)

Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Вход в систему

Что такое OpenID?
  • Регистрация
  • Забыли пароль?

Документация

  • Drupal 6
  • Константы
  • Файлы
  • Функции
  • Глобальные переменные
  • Разделы