Обновление тем 5.x до 6.x

Использование файлов .info

В Drupal 5 для хранения мета-данных модулей (название, описание, версия, зависимости и т.д.) стали использоваться файлы с расширением .info. Начиная с версии Drupal 6, темы также используют файлы .info.

Пример файла themeName.info (часть файла):

name = Theme Name
description = One sentence description of theme.
core = 6.x
engine = phptemplate

Реестр темы

Все функции темы теперь должны быть зарегистрированы. В Drupal 5 они обнаруживались на лету, в Drupal 6 для регистрации темы используется hook_theme(). PHPTemplate самостоятельно позаботится о регистрации темы, таким образом в большинстве случаев вам не нужно беспокоиться о ручной регистрации темы.

Здесь есть одно исключение. Формы, которые не используют шаблоны, не будут зарегистрированы. Подробную информацию можно найти на странице The theme registry for special cases.

Отметьте: каждый раз когда вы добавляете в тему новую функцию или шаблон, реестр должен быть очищен! Вы можете использовать модуль Devel, включив его блок и пользуясь ссылкой очистки реестра или использовать функцию drupal_rebuild_theme_registry() поместив её в файл template.php на время создания и тестирования темы.

Theming through template files

В Drupal 5, вы переопределяли функции используя themeEngine_hook() или themeName_hook(). Все переопределения должны были размещать в файле template.php и возвращать определённые данные.

Для использования функций в отдельных файлах шаблонов (.tpl.php), использовалась функция _phptemplate_callback().

<?php
function _phptemplate_variables($hook, $variables) {
  switch (
$hook) {
    case
'page':
     
// process variables for page hook.
   
break;
    case
'node':
    
// process variables for node hook.
   
break;
  }
  return
$variables;
}
?>

В Drupal 6 _phptemplate_callback() больше не поддерживается. Её возможности перемещены в функцию theme(). Пока функция зарегистрирована как шаблон, будет использоваться файл шаблона.

PHPTemplate автоматически регистрирует hook как обычную функцию или шаблон. Для регистрации функции в качестве шаблона, вам нужно сделать файл шаблона с названием функции. Например, для оформления hook'а menu_tree, сделайте в папке темы файл с названием menu-tree.tpl.php. Отметьте: знак подчёркивания заменён дефисом. Очистите реестр и шаблон будет использоваться.

Функция переменных _phptemplate_variables() больше неверна. Она использует новую форму с некоторыми важными изменениями.

  • Variables are now passed by reference
  • Each hook can have their own variable function.
  • The arguments $variables and $hook are used for all variable functions.
  • Multiple variable functions can run for each hook.
  • The following are the functions that PHPTemplate registers automatically:
    • phptemplate_preprocess()
    • phptemplate_preprocess_HOOK()
    • themeName_preprocess()
    • themeName_preprocess_HOOK()
  • PHPTemplate can register variable functions for your theme as long as a template file for the hook exists inside the theme.
  • These variable functions are also known as "preprocess functions"

For the "menu_tree" hook, $say_hi would be made available inside menu-tree.tpl.php.

<?php
function themeName_preprocess_menu_tree(&$variables) {
 
$variables['say_hi'] = "hello menu_tree";
}
?>

This may seem more complicated at first but it allows a great enhancement to themers. Module authors can now implement themable functions as templates by default. Simply copying over the template into your theme will force Drupal to use your copy. No need for complicated setups with callbacks. Just remember to clear the registry.

Управление шаблонами

Управление файлами шаблонов теперь стало легче благодаря возможности их организации в подпапки. PHPTemplate найдёт все шаблоны темы и зарегистрирует их положение (адрес). Ограничения на глубину вложения нет.

Новые файлы шаблонов (.tpl.php)

В Drupal 5, PHPTemplate обрабатывались следующие файлы шаблонов (внутри папки движка или папки темы):

Дальнейшая работа над системой шаблонов привела к использованию в Drupal 6 большего количества стандартных шаблонов и правил создания своих шаблонов. Для переопределения этих какого-либо шаблона, его нужно скопировать в папку темы и очистить реестр темы. Шаблоны, которые используются стандартными модулями можно посмотреть на странице Модули и их шаблоны.

Редко используемые стандартные функции из упомянутых выше шаблонов больше в них не используются. Например, функция theme_page. Её возможности теперь перенесены в шаблоны и в её использовании нет необходимости. Отметьте: не путайте удалённые функции с другими из-за похожести их названий, theme('page') по-прежнему работает.

Новый стандарт именования шаблонов

Шаблоны могут использовать дополнительные названия для page.tpl.php — на основе пути, для node.tpl.php — на основе типа документов, для block.tpl.php — на основе регионов и модулей. См. полный список на странице Именование шаблонов.

Определение регионов для блоков

Определение через hook_regions больше не существует. Регионы теперь определяются в файле .info. Для определения регионов в этом файле используйте секцию regions[]. Пример:

regions[left] = Left sidebar
regions[right] = Right sidebar
regions[content] = Content
regions[header] = Header
regions[footer] = Footer

Изменены названия переменных выводящих регионы

В Drupal 5 для вывода регионов left, right и footer, в файле page.tpl.php использовались переменные $sidebar_left, $sidebar_right и $footer_message. Эти названия остались ещё с версии 4.6.x и более ранних.

Чтобы сделать названия переменных проще, в Drupal 6, они переименованы в $left, $right и $footer, т.е. их названия стали соответствовать названиям регионов. Переменная $footer_message по-прежнему используется, но теперь она выводит информацию из поля Штамп страницы информации о сайте.

Параметры темы

Theme authors can now make their theme easily customizable by site administrators.

In the Drupal administration section, each theme has its own settings page at admin/build/themes/settings/themeName. And this page has a form with standard settings like “Logo image settings” and “Shortcut icon settings.” To add additional settings to the form, simply create a theme-settings.php file in the theme's directory and add a themeName_settings() or themeEngineName_settings() function. The function should use the Forms API to create the additional form widgets.

See the Custom theme settings page in the Theme developer's handbook for full details.

Переменная $signature

В Drupal 6 подписи пользователей сделаны динамическими. Это значит, что они могут показываться вместе с комментариями, но частью комментария не являются. Выводом подписей занимается переменная $signature, которую можно использовать в файле comment.tpl.php.

Drupal 5:

<div class="content">
  <?php print $content; ?>
</div>

Drupal 6:

<div class="content">
  <?php print $content ?>
  <?php if ($signature): ?>
    <div class="user-signature clear-block">
      <?php print $signature ?>
    </div>
  <?php endif; ?>
</div>

Отметьте: для предотвращения дублирования подписей в старых сообщениях, вам нужно использовать следующую запись:

<div class="content">
  <?php print $content ?>
  <?php if ($signature && $comment->cid > 3443): // The highest comment ID before upgrading to Drupal 6 ?>
    <div class="user-signature clear-block">
      <?php print $signature ?>
    </div>
  <?php endif; ?>
</div>

Переменная $body_classes

Inside "page.tpl.php" getting the state of the layout was possible with this:

Drupal 5:

<?php print $layout; ?>

would print left, right, or both depending on the sidebars in use.

Drupal 6:

<?php print $body_classes; ?>

may retrieve something like:

front logged-in node-type-page no-sidebars

which offers a set of specialized classes like those seen above. You can learn more at http://drupal.org/node/171906

Переменная $language теперь является объектом

Переменная $language доступная в темах PHPTemplate теперь не просто строка выводящая код языка текущей страницы, теперь это объект? который позволяет определять свойства текущего языка, что позволяет делать темы для языков использующих письмо справа налево.

$language has the $language->language property available with the current language code, and $language->direction being an intereger (0 or LANGUAGE_LTR for left to right and 1 or LANGUAGE_RTL for right to left). If you are only interested in updating your themes, just change every instance of $language to $language->language.

Переопределение CSS файлов определённых модулями

Themes may replace module-defined CSS files by adding a stylesheet with the same filename using drupal_add_css(). This allows themes to override complete CSS files, rather than specific selectors, when necessary.

For example, if the following code were placed in Garland’s template.php file, themes/garland/system-menus.css would replace modules/system/system-menus.css.

<?php
drupal_add_css
(path_to_theme() .'/system-menus.css', 'theme');
?>

Right to left CSS override files supported

To better support languages that flow right to left, any CSS file added to the page with drupal_add_css() can have a right to left CSS file pair. An example could be style.css, which can have a style-rtl.css file in the same directory. This file can contain overrides for the stlyes in style.css which should be different in a right to left language. The Drupal core system includes such RTL CSS files for built-in modules as well as some themes. By convention, the overriden rules are marked with an /* LTR */ comment in the original CSS file, so maintainers will notice that the RTL CSS might need modification when modifying the original CSS file later. These CSS files are only loaded when an RTL language is used to display the page.

An excerpt from the modules/system/defaults.css file:

th {
  text-align: left; /* LTR */
  padding-right: 1em; /* LTR */
  border-bottom: 3px solid #ccc;
}

An excerpt from the modules/system/defaults-rtl.css file:

th {
  text-align: right;
  padding-right: inherit;
  padding-left: 1em;
}

Submitted by user on date/time is themable

The "submitted" element in nodes and comments is now themable just like any themable element. This means that you can override what information is included, and how it is presented.

You can add custom id/class, you can include more or less info, or even make the submitted look different for comments or node types.

For an example, see the template.php file for the garland theme.

jQuery обновлена до вересии 1.2.3

Библиотека JavaScript jQuery включённая в Drupal обновлена до версии1.2.3.

Файл JavaScript

Также как и файл style.css, теперь из папки темы автоматически загружается файл с названием script.js. Название этого файла можно изменить в файле .info.

JavaScript themeing

There is now a themeing mechanism for JavaScript code. Together with the automatically included script.js, this allows theme developers more freedom in the domain of scripted events on Drupal webpages. Often, JavaScript code produces markup that is inserted into the page. However, this HTML code has usually been hardcoded into the script, which did not allow alteration of the inserted code.

Modules provide default theme functions in the Drupal.theme.prototype namespace. Themes should place their override functions directly in the Drupal.theme namespace. Scripts call Drupal.theme('function_name', ...) which in turn decides whether to call the function provided by the theme (if present) or the default function.

JavaScript theme functions are entirely free in their return value. It can vary from simple strings, up to complex data types like an object containing in turn several jQuery objects which are wrapped around DOM elements. See the original (default) theme function to see what your custom theme function should return.

CSS class selector changes

The class attribute for active menu items has changed from a.active to a.active-trail. This affects the CSS for the active primary and secondary links as ul.primary-links li a.active and ul#secondary-nav li a.active which now is should be referred to as ul.primary-links li a.active-trail and ul#secondary-nav li a.active-trail.