Обзор изменений в темах
В Drupal 5 для хранения мета-данных модулей (название, описание, версия, зависимости и т.д.) стали использоваться файлы с расширением .info. Начиная с версии Drupal 6, темы также используют файлы .info. См. инструкции по написанию .info-файлов.
Пример файла themeName.info (часть файла):
name = Theme Name
description = One sentence description of theme.
core = 6.x
engine = phptemplateВсе функции темы теперь должны быть зарегистрированы. В Drupal 5.x они обнаруживались на лету, в версии 6.x для регистрации темы используется hook_theme(). PHPTemplate самостоятельно позаботится о регистрации темы, таким образом в большинстве случаев вам не нужно беспокоиться о ручной регистрации темы.
There is one exception to this. Forms that do not have a default theme implementation will not be registered. See the example in the theming handbooks for more details.
Отметьте: каждый раз когда вы добавляете в тему новую функцию или шаблон, реестр должен быть очищен! Вы можете использовать модуль Devel, включив его блок и пользуясь ссылкой очистки реестра или использовать функцию drupal_rebuild_theme_registry() поместив её в файл template.php на время создания и тестирования темы.
В 5.x, вы переопределяли функции используя 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;
}
?>В 6.x, _phptemplate_callback() больше не поддерживается. Её возможности перемещены в функцию theme(). Пока функция зарегистрирована как шаблон, будет использоваться файл шаблона.
Registering as a normal function works just like overridding with "themeEngine_hook()" or "themeName_hook()" without the callback in 5.x.
PHPTemplate автоматически регистрирует hook как обычную функцию или шаблон. Для регистрации функции в качестве шаблона, вам нужно сделать файл шаблона с названием функции. Например, для оформления hook'а menu_tree, сделайте в папке темы файл с названием menu-tree.tpl.php. Отметьте: знак подчёркивания заменён дефисом. Очистите реестр и шаблон будет использоваться.
The variable function "_phptemplate_variables()" is no longer valid. It takes a new form with a few important points to be aware of.
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.
Управление файлами шаблонов (.tpl.php) теперь стало легче благодаря возможности их организации в подпапки. PHPTemplate найдёт все файлы в папке темы и зарегистрирует их положение (адрес). Ограничения на глубину вложения нет.
В 5.x PHPTemplate обрабатывались следующие файлы шаблонов (внутри папки движка):
With the new changes under the hood, more default templates are provided and more will be available in future releases. The ones from PHPTemplate in 5.x were also moved. Read the comments inside these files to see where they are used and the available variables.
In order to override these templates, all you need to do is copy them into your theme folder and clear the theme registry.
See the complete list of new templates in the theming handbook.
The seldom used default core functions for the above templates are no longer present. For example, theme_page no longer exists. This affects all themable output converted into templates. Due to the nature of the change, they are no longer necessary. This change should not affect anyone. Do not confuse the removed functions with how they are called. theme('page') still works. It is the default implementation that has changed.
Template suggestions existed for page.tpl.php -based on path, node.tpl.php -based on node type and block.tpl.php -based on regions and modules. With the template conversions mentioned above, new suggestions are also provided.
See the complete list of new template suggestions in the theming handbook.
"hook_regions" has been deprecated. Regions are now defined through .info files. More details available in the main handbook page.
regions[left] = Left sidebar
regions[right] = Right sidebar
regions[content] = Content
regions[header] = Header
regions[footer] = FooterВ Drupal 6.x изменены названия переменных выводящих левую, правую и нижнюю колонки. В 5.x для вывода регионов left, right и footer, в файле page.tpl.php использовались переменные $sidebar_left, $sidebar_right и $footer_message. Эти названия остались ещё с версии 4.6.x и более ранних.
Чтобы сделать названия переменных проще, они переименованы в $left, $right и $footer, т.е. их названия стали соответствовать названиям регионов. Переменная $footer_message по-прежнему используется, но теперь она выводит информацию из поля Footer messege со страницы Site information.
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.
В Drupal 6.x подписи сделаны динамическими. Это значит, что они показываются вместе с комментариями, но частью комментария не являются. Выводом подписей занимается переменная $signature, которую можно использовать в файле comment.tpl.php.
В 5.x:
<div class="content">
<?php print $content; ?>
</div>В 6.x:
<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>Inside "page.tpl.php" getting the state of the layout was possible with this:
В 5.x:
<?php print $layout; ?>would print left, right, or both depending on the sidebars in use.
В 6.x $body_classes are also available:
<?php print $body_classes; ?>may retrieve something like:
front logged-in node-type-page no-sidebarswhich offers a set of specialized classes like those seen above. You can learn more at http://drupal.org/node/171906
Переменная $language доступная в темах PHPTemplate теперь не просто строка выводящая код языка текущей страницы, теперь это объект который позволяет определять свойства текущего языка. Теперь вы можете делать темы совместимые с письмом справа налево (пример: http://www.drupal.org.il/).
$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.
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');
?>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;
}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.
Библиотека JavaScript jQuery включённая в Drupal обновлена до версии1.2.3.
Также как и файл style.css, теперь из папки темы автоматически загружается файл с названием script.js. Название этого файла можно изменить в файле .info.
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.
Comments
Post new comment