Обновление тем 6.x до 7.x
- Стандартные блоки получили читаемые идентификаторы CSS ID
- Основные и Дополнительные ссылки переименованы в Основное и Дополнительное меню
- Переменная $taxonomy удалена из шаблона node.tpl.php
- Соответствие стандарту RDF требует изменений в начале файла page.tpl.php
- Класс clear-block переименован в clearfix
- Шаблон box.tpl.php удалён
- Переменная $help стала регионом
- Переменная $mission удалена. Взамен введён регион highlight
- Переменная $footer_message удалена
- Регион content стал обязательным; содержание документа стало блоком
- Second phase variable process functions
- HTML classes generated through a variable
- HTML-атрибуты генерируются переменными
- Variable process functions can now be used for all theming hooks
- All theme functions now take a single argument, $variables
- Названия функций обязаны совпадать с названием темы
- All CSS and JavaScript files must be specified in the theme's .info file
- Переменная $block->content переименована в $content (файл block.tpl.php)
- Granular rendering in node and user templates
- jQuery UI 1.7 добавлена в ядро
- JavaScript и CSS прикреплены к drupal_render
- Переменная $closure переименована в $page_bottom; добавлена $page_top и скрытые регионы
- Переменные $left и $right переименованы в $sidebar_first и $sidebar_second
- Переменная $picture changes переименована в $user_picture
- New classes available to hide content in an accessible manner
- Переменная JavaScript Drupal.jsEnabled удалена
- В PHPTemplate стало возможным использование масок
- Include theme definition explicitly on element when using system_elements()
- Добавлена разметка, делающая процесс установки понятным для пользователей скрин-ридеров
- theme_breadcrumb() добавлены невидимые заголовки
- Изменены атрибуты alt и title значка RSS
- Вывод формы поиска перемещён из шаблонов тем в блоки
- Changes to menu tree, link and tab rendering functions
- theme_links() has a new parameter $heading for accessibility
- theme_get_setting() and THEME_settings() have been improved
- theme_form_required_marker()
- theme_link()
- Skip to main content links in core themes
- Alter hooks available to themes
- Изменены стили модуля System
- Темам добавлен параметр, определяющий вывод значков для добавления ярлыка страницы
- Для перекрытия шаблонов используются два дефиса вместо одного
- CSS-файлы иногда загружаются через @import, иногда через LINK
- CSS-файлы для определённых браузеров добавляются с использованием drupal_add_css()
Стандартные блоки получили читаемые идентификаторы CSS ID
Стандартные блоки получили идентификаторы, которые позволяют определить назначение блока из названия его идентификатора.
| Блок | Drupal 6 CSS ID | Drupal 7 CSS ID |
|---|---|---|
| Новое в блогах | block-blog-0 | block-blog-recent |
| Меню книги | block-book-0 | block-book-navigation |
| Новые комментарии | block-comment-0 | block-comment-recent |
| Обсуждаемые темы | block-forum-0 | block-forum-active |
| Новое на форуме | block-forum-1 | block-forum-new |
| Выбор языка | block-locale-0 | block-locale-language-switcher |
| Лента сайта | block-node-0 | block-node-syndicate |
| Последний опрос | block-poll-0 | block-poll-recent |
| Автор документа | block-profile-0 | block-profile-author-information |
| Форма поиска | block-search-0 | block-search-form |
| Популярное содержание | block-statistics-0 | block-statistics-popular |
| Система — Drupal | block-system-0 | block-system-powered-by |
| Вход в аккаунт | block-user-0 | block-user-login |
| Навигация | block-user-1 | block-user-navigation |
| Новые пользователи | block-user-2 | block-user-new |
| Сейчас на сайте | block-user-3 | block-user-online |
Соответственно изменились и описания стилей. Например:
Drupal 6
/* Make the text in the user login block bigger. */
#block-user-0 {
font-size: 1.5em;
}Drupal 7
/* Make the text in the user login block bigger. */
#block-user-login {
font-size: 1.5em;
}Основные и Дополнительные ссылки переименованы в Основное и Дополнительное меню
В темах, которые используют эти меню, должны быть обновлены их переменные:
Drupal 6
<div id="menu">
<?php if (isset($secondary_links)) { ?><?php print theme('links', $secondary_links, array('class' => 'links', 'id' => 'subnavlist')); ?><?php } ?>
<?php if (isset($primary_links)) { ?><?php print theme('links', $primary_links, array('class' => 'links', 'id' => 'navlist')) ?><?php } ?>
</div>Drupal 7
<div id="menu">
<?php if (isset($secondary_menu)) { ?><?php print theme('links', $secondary_menu, array('class' => 'links', 'id' => 'subnavlist')); ?><?php } ?>
<?php if (isset($main_menu)) { ?><?php print theme('links', $main_menu, array('class' => 'links', 'id' => 'navlist')) ?><?php } ?>
</div>Переменная $taxonomy удалена из шаблона node.tpl.php
Раньше, переменная $taxonomy использовалась для доступа к массиву невыводимых ссылок таксономии текущего документа.
В Drupal 7, все ссылки перемещены в объект $node. Для доступа к массиву невыводимых ссылок таксономии теперь используется запись node->content['links']['terms']['#value'].
Выводимые ссылки таксономии не затронуты; шаблон node.tpl.php может получить к ним доступ через переменную $terms как и ранее. В шаблонах тем для Drupal 6 нужно заменить переменную $taxonomy на переменную $terms, как показано в примере ниже.
Drupal 6
<?php if ($taxonomy): ?>
<div class="terms"><?php print $terms ?></div>
<?php endif;?>Drupal 7
<?php if ($terms): ?>
<div class="terms"><?php print $terms ?></div>
<?php endif;?>Соответствие стандарту RDF требует изменений в начале файла page.tpl.php
Drupal 7 использует вывод RDF, который требует следующих изменений в шаблоне page.tpl.php.
- DOCTYPE нужно изменить на XHTML+RDFa 1.0.
- Для соответствия стандарту XHTML 1.1, атрибут
langнужно удалить, оставив толькоxml:lang. - Префиксы пространства имён RDF используемые в HTML-документе должны быть преобразованы в теге
htmlи содержаться в переменной$rdf_namespaces. - Профиль GRDDL нужно определить в теге
<head>.
Drupal 6
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language ?>" lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>">
<head>Drupal 7
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>"
<?php print $rdf_namespaces ?>>
<head profile="<?php print $grddl_profile ?>">Класс clear-block переименован в clearfix
Наименование класса clear-block использовалось в Drupal для тех же целей, в которых используется класс clearfix в среде разработчиков CSS. Также, использование слова block смущало пользователей Drupal, которые больше знакомы с системой блоков системы, чем со свойствами в наборах правил CSS. Название этого класса изменено для того, чтобы не смущать новых разработчиков тем сообщества Drupal.
Drupal 6:
<div class="clear-block">
...
</div>Drupal 7:
<div class="clearfix">
...
</div>Шаблон box.tpl.php удалён
У тех частей содержания, которые использовали этот шаблон теперь есть свои функции. Списки результата поиска теперь оформляются с помощью функции theme_search_results_listing(), а бокс формы комментариев с помощью функции theme_comment_form_box()
Переменная $help стала регионом
В Drupal 7 к стандартным регионам (left, right, content, header, footer), добавлен новый регион help. По умолчанию, содержание этого региона соответствует содержанию переменной $help шаблона page.tpl.php Drupal 6.
regions[help] = HelpСправочный текст окружён в шаблоне block.tpl.php тегом <div>, который используется для его оформления с помощью CSS.
Переменная $mission удалена. Взамен введён регион highlight
(issue) В Drupal 6 шаблон темы получал специальную переменную, которая называлась $mission, которая занималась выводом миссии (текст вводился на странице Информация о сайте) сайта на его первой странице. Темы Drupal 6 также имели параметр вывода этой переменной на странице настройки темы. В Drupal 7 удалены параметры настройки миссии и переключателя её включения на сайте со страницы тем в пользу более настраиваемых блоков, которые можно разместить в любых регионах и для которых доступно большее количество параметров вывода.
По умолчанию, Drupal 7 теперь включает в себя регион с названием highlight, который теперь используется для вывода миссии. Содержание этого региона окружено тегами <div> в шаблоне block.tpl.php, используются свои классы CSS, что позволяет легко оформить миссию нужным вам образом.
Если в используемой вами дополнительной теме нет этого региона, то достаточно будет лишь добавить этот регион в .info-файл темы точно так же, как и другие регионы:
regions[content] = Content
regions[left] = Left sidebar
regions[help] = HelpПеременная $footer_message удалена
(issue) В Drupal 6 шаблон темы получал специальную переменную, которая называлась $footer_message и занималась выводом информации в нижней колонке (нижнем регионе). В шаблоне эта переменная обычно использовалась перед переменной $footer. По сути, это сообщение было лишь отдельным блоком и поэтому в Drupal 7 эта переменная удалена в пользу блока, который имеет более широкие настройки.
Для обновления своих тем, просто удалите переменную $footer_message из своих шаблонов.
Если в используемой вами дополнительной теме нет региона $footer, то достаточно будет лишь добавить этот регион в .info-файл темы точно так же, как и другие регионы:
regions[footer] = FooterРегион content стал обязательным; содержание документа стало блоком
(issue) В Drupal 6 переменная $content файла page.tpl.php занималась выводом содержания документа. Содержание документа могло быть окружено регионами и располагающимися в них блоками, но сама эта переменная в другой регион перемещена быть не могла.
В Drupal 7 переменная $content стала полноценным регионом и обязательна для всех тем. Это требование введено из-за того, что при включении темы Друпал должен знать где разместить основное содержание страницы по умолчанию.
В Drupal 6 можно было только разместить блоки после основного содержания страницы в этом регионе. Единственным путём разместить блок до основного содержания было определение отдельного региона для этих целей. Drupal 7 теперь делает основное содержание страницы таким же блоком как и остальные. Это делает возможным размедение в этом регионе блоков как после, так и до основного содержания без необходимости создания ещё одного региона.
В связи с этими изменениями основное содержание теперь обёрнуто разметкой определённой в шаблоне block.tpl.php. И если ранее класс .block применялся только к блокам расположенным в сайдбарах (левой и правой колонках/регионах), то в Drupal 7 этот класс будет применён и к содержанию документа, поэтому правки требуют .css-файлы, которые описывают класс .block. Вам потребуется конкретизировать этот класс добавив в него название региона, например #left-sidebar .block.
Second phase variable process functions
There are now two sets of variables process functions. The first are the existing "preprocess" functions. The second are "process" functions which are run after preprocessors. All the various prefixes and suffixes apply to this second phase in the exact same way. This is useful when certain variables need to be worked on in two phases.
For example, adding classes into an array for the "preprocess" phase then flattening them into a string in the "process" phase so it's ready to print within a template. See next section.
HTML classes generated through a variable
All templates can now print out $classes from a template to render dynamic classes built from variable process functions. The way to add these dynamic classes is by feeding the variable key labeled "classes_array" like so:
<?php
function mytheme_preprocess_node(&$vars) {
// Add a striping class.
$vars['classes_array'][] = 'node-' . $vars['zebra'];
}
?>The default "template_process" (second phase processor) will take care of flattening the array into a flat string making it ready to print from your template. Dynamic classes are generated for common templates by default but due to the way it's set-up, any template can have a $classes variable.
Example:
<div class="<?php print $classes ?>">
...
</div>HTML-атрибуты генерируются переменными
All templates can now print out $attributes, $title_attributes, and $content_attributes from a template to render dynamic attributes built from variable process functions. The RDF module and other modules add important information to these variables, so it is important for themes to ensure that these variables are printed correctly within all overridden template files. These three variables contain attributes for the overall element being rendered by the template, and its primary title and content elements, respectively. The way to add attributes to these variables is by feeding the variable keys labeled "attributes_array", "title_attributes_array", and "content_attributes_array" like so:
<?php
function mytheme_preprocess_node(&$vars) {
// If the node was saved with a log message and the currently logged in user
// has permission to view that message, add it as a title attribute (tooltip)
// when displaying the node.
if (!empty($vars['node']->log) && user_access('view revisions')) {
$vars['attributes_array']['title'] = $vars['node']->log;
}
// Force the direction of node titles to be left to right, regardless of
// language or any other settings.
$vars['title_attributes_array']['dir'] = 'ltr';
}
?>The default "template_process" (second phase processor) takes care of flattening the arrays into strings ready to print within the template file. The flattening process results in either empty strings (if no dynamic attributes were set) or strings that have a leading space followed by attribute names and values. Because of this, the attributes variables should be printed directly next to what precedes it in the template, with no leading space.
Example:
<div id="..." class="..."<?php print $attributes; ?>>
<h2<?php print $title_attributes; ?>>...</h2>
<div class="content"<?php print $content_attributes; ?>>...</div>
</div>As is shown in the example, the convention is for the "id" and "class" attributes to be printed explicitly within the template, and for the attributes variables to be used for all other attributes. Therefore, to ensure that no attribute gets printed twice within the same element, the following rules should be followed:
- Preprocess functions within modules must not add "id" or "class" to the attributes arrays.
- Preprocess functions within themes may add "id" and/or "class" to the attributes arrays, but if they do so, the theme must also override the corresponding template file and ensure that the same attribute isn't being printed explicitly.
- Templates must not print any attribute other than "id" or "class" explicitly on any element for which an attributes variable is also being printed. Instead, the theme must use a preprocess function, as shown above.
Variable process functions can now be used for all theming hooks
(issue) In Drupal 6, preprocess functions could only be used for theming hooks rendered by templates. In Drupal 7, hook-specific preprocess and process functions can be used for all theming hooks, whether rendered by templates or functions. For example, a theme can make all menu links that start with "http:" or "https:" (as opposed to ones that refer to an internal drupal path) to open in a new browser tab:
<?php
function mytheme_preprocess_menu_link(&$variables) {
if (
substr($variables['element']['#href'], 0, 5) == 'http:' ||
substr($variables['element']['#href'], 0, 6) == 'https:'
) {
$variables['element']['#localized_options']['attributes']['target'] = '_blank';
}
}
?>Every preprocess function adds to the time it takes to theme the item, so especially for theme functions that get called a lot, keep an eye on performance when adding preprocess functions.
To minimize performance overhead, the non-hook-specific preprocess and process functions are called for templates only. See the API documentation for theme() for the full list of hook-specific and non-hook-specific preprocess and process functions.
All theme functions now take a single argument, $variables
(issue) In Drupal 6, theme functions registered their function arguments in hook_theme(). In Drupal 7, all theme functions take a single argument, $variables, an array of keyed variables, and register the expected keys within this array in hook_theme().
6.x
<?php
function drupal_common_theme() {
return array(
...
'table' => array(
'arguments' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL),
),
...
);
}
function theme_table($header, $rows, $attributes = array(), $caption = NULL) {
...
}
?>7.x
<?php
function drupal_common_theme() {
return array(
...
'table' => array(
'variables' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL, 'colgroups' => array(), 'sticky' => TRUE),
),
...
);
}
function theme_table($variables) {
$header = $variables['header'];
$rows = $variables['rows'];
$attributes = $variables['attributes'];
$caption = $variables['caption'];
$colgroups = $variables['colgroups'];
$sticky = $variables['sticky'];
...
}
?>Названия функций обязаны совпадать с названием темы
Названия функций в файле template.php теперь обязаны совпадать с названием темы. Не стоит использовать phptemplate_function. Это изменение сделано в патче: Die, themeEngineName_ prefix, die!. При обновлении темы, убедитесь что названия функций в файле template.php (и других подключенных файлах) не начинаются с названия движка шаблонов (phptemplate).
All CSS and JavaScript files must be specified in the theme's .info file
В Drupal 6, файлы style.css и script.js могли быть включены в тему автоматически, даже если и не были определены в файле .info. В Drupal 7, подключение этих файлов должно быть явно определено в файле .info. Дополнительную информацию об этом изменении вы можете найти в документе Remove default values for stylesheet and scripts includes from system module. Если вашей теме не нужны эти файлы, или нужны и они уже явно определены, то изменений не потребуется.
Переменная $block->content переименована в $content (файл block.tpl.php)
Изменение связано с упрощением кода. Подробнее смотрите документ Simplify block rendering.
Granular rendering in node and user templates
(issue) Template authors may now finally print out bits of node and profile content as they see fit and still maintain forward compatibility with new modules that might add new content. To do so, template authors should use 2 new functions - render() and hide(). Example taken from node.tpl.php:
<div class="content">
<?php
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
print render($content);
?>
</div>
<?php print render($content['links']); ?>
<?php print render($content['comments']); ?>render() returns all the items that are in $content. So, print render($content) is equivalent to the D6 print $content. When a templater wants to print out part of the $content array, she may do so with something like print render(content['links']). If the printing of links comes after the printing of all the rest of $content, then templater should call hide($content['links']) before calling print render($content). Then, the links can be printed further down in the template with print render($content['links']).
jQuery UI 1.7 добавлена в ядро
(issue) Вы можете найти файлы jQuery UI в папке misc/ui и при необходимости добавлять файлы JavaScript и CSS используя drupal_add_js() и drupal_add_css(). Если вы обновляете тему, для которой использовался дополнительный модуль работающий с jQuery UI, то обратитесь к документу Converting 6.x modules to 7.x.
JavaScript и CSS прикреплены к drupal_render
(issue) Введена возможность связывать определённые элементы интерфейса с определёнными JavaScript и CSS. Подробнее это сформулировано в документах #attached_js и #attached_css.
Drupal 6.x:
<?php
function example_admin_settings() {
// Add example.admin.css
drupal_add_css(drupal_get_path('module', 'example') .'/example.admin.css');
// Add some inline JavaScript
drupal_add_js('alert("You are visiting the example form.");', 'inline');
// Add a JavaScript setting.
drupal_add_js(array('mymodule' => 'example'), 'setting');
$form['example'] = array(
'#type' => 'fieldset',
'#title' => t('Example');
);
return $form;
}
?>Drupal 7.x:
<?php
function example_admin_settings() {
$form['#attached_css'] = array(
// Add example.admin/css.
drupal_get_path('module', 'example') . '/example.admin.css'
),
$form['#attached_js'] = array(
// Add some inline JavaScript.
'alert("You are visiting the example form.");' => 'inline',
// Add a JavaScript setting. Note that when the key is a number, the 'data' property will be used.
array(
'data' => array('mymodule' => array(...)),
'type' => 'setting'
),
);
$form['example'] = array(
'#type' => 'fieldset',
'#title' => t('Example');
);
return $form;
}
?>Переменная $closure переименована в $page_bottom; добавлена $page_top и скрытые регионы
(issue 1, issue 2) В Drupal 6 существовала переменнная $closure, которая размещалась перед HTML-тегом <body> и могла быть обработана через theme_footer() (которая могла быть обработана через hook_footer() в модуле). To generalize on one way to put output to the different page areas, Drupal 7 standardizes on regions and introduced the page_bottom region in place of the $closure special variable. Also, page_top is added as a pair of page_bottom. In Drupal 7 you need to output $page_top at the top of the HTML body output and $page_bottom at the bottom.
Drupal 6:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
...
<body class="<?php print $body_classes; ?>">
...
<?php print $closure; ?>
</body>
</html>Drupal 7:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
...
<body class="<?php print $classes; ?>">
<?php print $page_top; ?>
...
<?php print $page_bottom; ?>
</body>
</html>Когда вы самостоятельно определяете дополнительные регионы, важно помнить, что в набор регионов необходимо включить регионы page_top и page_bottom.
regions[content] = Content
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottomРегионы page_top и page_bottom являются скрытыми. Это означает, что они не показываются на странице блоков. При создании специфичных тем, может быть целесообразным создание дополнительных скрытых регионов. Например, чтобы дать возможность модулям выводить свои данные в большем количестве областей темы без создания и вывода блоков на страницу блоков. Определить скрытый регион можно используя запись regions_hidden[] в файле .info:
regions[content] = Content
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[indicators] = Indicators
regions_hidden[] = indicatorsПеременные $left и $right переименованы в $sidebar_first и $sidebar_second
(issue) В Drupal 6 переменные использовавшиеся для левой и правой колонок (регионов) назывались $left и $right. В Drupal 7 они переименованы в $sidebar_first и $sidebar_second.
Drupal 6
<?php if (!empty($left)): ?>
<div id="sidebar-left" class="column sidebar">
<?php print $left; ?>
</div> <!-- /sidebar-left -->
<?php endif; ?>
...
<?php if (!empty($right)): ?>
<div id="sidebar-right" class="column sidebar">
<?php print $right; ?>
</div> <!-- /sidebar-right -->
<?php endif; ?>Drupal 7
<?php if ($sidebar_first): ?>
<div id="sidebar-first" class="column sidebar"><div class="section region">
<?php print $sidebar_first; ?>
</div></div> <!-- /.section, /#sidebar-first -->
<?php endif; ?>
<?php if ($sidebar_second): ?>
<div id="sidebar-second" class="column sidebar"><div class="section region">
<?php print $sidebar_second; ?>
</div></div> <!-- /.section, /#sidebar-second -->
<?php endif; ?>Также изменились CSS ID применявшиеся к этим переменным:
Drupal 6:
.sidebar-left
.sidebar-right
Drupal 7:
.sidebar-first
.sidebar-second
Переменная $picture changes переименована в $user_picture
Названия переменной и класса стали более читаемыми.
Drupal 6 (user-picture.tpl.php):
<div class="picture">
<?php print $picture; ?>
</div>Drupal 7:
<?php if ($user_picture): ?>
<div class="user-picture">
<?php print $user_picture; ?>
</div>
<?php endif; ?>New classes available to hide content in an accessible manner
Для скрытия элементов страницы введены два новых класса: .element-hidden и .element-invisible. Каждый класс используется для своих целей:
.element-hidden
Назначение этого класса — скрывать элементы от всех пользователей. Этот класс должен использоваться для элементов, для которых не требуется их немедленный показ на странице. Например, это может быть свёрнутый элемент , который может быть раскрыт пользователем при клике мышкой. Эффект оказываемый этим классом может быть применён и с использованием функций jQuery — show() и hide().
.element-invisible
Назначение этого класса — скрывать элементы визуально, но сохранить их доступность для скрин-ридеров. Этот класс должен использоваться для элементов, которые предназначены для пользователей скрин-ридеров и обычный показ которых на странице неудобен. Информация выводимая в таком классе должна быть краткой, но ёмкой, для избежания излишней перегрузки информацией пользователя скрин-ридера. Этот класс не должен использоваться для фокусируемых элементов (таких как ссылки или элементы форм), так как в этом случае возникнут проблемы как у пользователей скрин-ридеров, так и пользователей которые скрин-ридером не пользуются.
Переменная JavaScript Drupal.jsEnabled удалена
В Drupal 6 вы могли проверить включенность JavaScript в браузере пользователя и переключиться на jQuery:
if( Drupal.jsEnabled ) {
// something
}В Drupal 7, переменная Drupal.jsEnabled удалена, т.к. вероятность того, что jQuery не будет работать в браузере с включенным JavaScript крайне низка. Подробности вы можете узнать в документе Kill the killswitch.
В PHPTemplate стало возможным использование масок
(issue) В Drupal 6 можно было использовать правило определённое для какого-либо одного конкретного шаблона, например page-user.tpl.php или page-user-1.tpl.php. Применение такого правило было громоздким, т.к. использование одного шаблона могло затронуть данные которые вы не хотели затрагивать или было недостаточным для изменения данных, которые вы хотели изменить.
Согласно новым правилам, в адресах шаблонов теперь можно использовать маску %, например page-user-%.tpl.php. Шаблоны для которых используются явно определённые аргументы (без маски), например page-user-edit.tpl.php, маски не затронут.
Include theme definition explicitly on element when using system_elements()
In system_elements(), it is now necessary to include the theme definition explicity on the element, rather than allowing the system to "fallback" and assign it automatically. Refer to issue 127731.
Добавлена разметка, делающая процесс установки понятным для пользователей скрин-ридеров
В Drupal 6 не было разметки, которая бы показывала текущие задачи процесса установки и их статус. Разница в статусе определялась только CSS. В Drupal 7 добавлена функция theme_task_list(), которая позволяет:
Добавить заголовки, которые видны только пользователям скрин-ридеров в том случае, если CSS выключены.
<h2 class="element-invisible">Installation tasks</h2>Добавить задачам текст (done) и (active), который будет также виден только пользователям скрин-ридеров и при выключенных CSS.
<span class="element-invisible">(done)</span>theme_breadcrumb() добавлены невидимые заголовки
В Drupal 6 не существовало разметки, показывающей пользователям скрин-ридеров то, что данные ссылки являются ссылками навигационной линейки.
В Drupal 7 добавлены заголовки перед списком ссылок навигационной линейки, которые видны пользователям скрин-ридеров и при выключенных CSS. Эти заголовки добавляются к содержанию выводящемуся функциями theme_breadcrumb() и garland_breadcrumb().
<h2 class="element-invisible">You are here</h2>Изменены атрибуты alt и title значка RSS
В Drupal 6 атрибут alt, который использовался для значка RSS и выводился функцией theme_feed_icon() был статически прописан как Syndicate content. Атрибут title брался из переменной $title.
В Drupal 7 атрибут alt для изображения и атрибут title для ссылки приведён к однообразию. Текст собирается из фразы «Subscribe to », к которой прибавляется значение переменной $title обработанной функцией theme_feed_icon().
Вывод формы поиска перемещён из шаблонов тем в блоки
В Drupal 6 форма search_box выводилась путём использования переменной $search_box в файле шаблона темы.
В Drupal 7 форма поиска это часть системы блоков. В шаблонах темы потребуется убрать переменную $search_box и изменить CSS для оформления формы поиска в блоке.
Changes to menu tree, link and tab rendering functions
(issue) function menu_tree_output() now returns a structured array of data that can be rendered to html using drupal_render().
Function theme_menu_item_link() and theme_menu_item() have been removed and are effectively replaced by in terms of rendering a menu tree by theme_menu_link(). This is the default function used to render each link in the tree returned by menu_tree_output().
Function theme_menu_local_task() takes different parameters and has a companion theme_menu_local_action() that did not exist in Drupal 6. Both of these function take as the first parameter a menu link array with 'title', 'href', and 'localized_options' keys. In Drupal 6, the first parameter was a string. The change to array was made in order to allow removal of theme_menu_item_link(). The second parameter theme_menu_local_task() of is still a boolean, $active.
Changes to menu tree, link and tab rendering functions
(issue) function menu_tree_output() now returns a structured array of data that can be rendered to html using drupal_render().
Function theme_menu_item_link() and theme_menu_item() have been removed and are effectively replaced by in terms of rendering a menu tree by theme_menu_link(). This is the default function used to render each link in the tree returned by menu_tree_output().
Function theme_menu_local_task() takes different parameters and has a companion theme_menu_local_action() that did not exist in Drupal 6. Both of these function take as the first parameter a menu link array with 'title', 'href', and 'localized_options' keys. In Drupal 6, the first parameter was a string. The change to array was made in order to allow removal of theme_menu_item_link(). The second parameter theme_menu_local_task() of is still a boolean, $active.
theme_links() has a new parameter $heading for accessibility
()">issue) To meet Web Content Accessibility Guidelines (WCAG) requirements, HTML headings should be used before all content sections, which includes lists of links such as menus. The headers ensure that there is a quick way for assistive technology users to browse through the content; however, most visual users do not need headers on navigation lists, because they can get a sense of the structure by how they are arranged visually on the page. So, the recommendation is to add a header with the "element-invisible" CSS class on it, so that only assistive technology users will notice the header.
It is also important that the header level used (H2, H3, etc.) be appropriately nested in the heading hierarchy. So, it is not recommended to just blindly add an H2 header before each list.
For that reason, the theme_links() function, which is normally called via theme('links', ...), has a new third parameter $heading to add the required heading to a list of links.
For example - Drupal 6 in a typical page.tpl.php file:
<?php print theme('links', $secondary_menu, array('id' => 'secondary-menu', 'class' => array('links', 'clearfix'))); ?>Drupal 7:
<?php print theme('links', $secondary_menu, array('id' => 'secondary-menu', 'class' => array('links', 'clearfix')), array('text' => t('Secondary menu'), 'level' => 'h2', 'class' => array('element-invisible'))); ?>This will result in a semantically correct and accessible secondary menu in Drupal 7, because an invisible heading has been added:
<h2 class="element-invisible">Secondary menu</h2>For more information:
theme_get_setting() and THEME_settings() have been improved
In Drupal 6, themes could add custom form elements to their “configure theme settings” page at admin/build/themes/settings/THEMENAME. Themes would need to create a theme-settings.php page in their theme directory and use a function with the following syntax:
<?php
/**
* Implementation of THEMEHOOK_settings() function.
*
* @param $saved_settings
* array An array of saved settings for this theme.
* @return
* array A form array.
*/
function phptemplate_settings($saved_settings) { }
?>In Drupal 7, much more flexibility is given to themes to modify the entire theme settings form. In a theme’s theme-settings.php, themes should now use a THEMENAME_form_system_theme_settings_alter(&$form, $form_state) function. This gives the same power to themes that modules have if they use hook_form_system_theme_settings_alter(). See the “Forms API Quickstart Guide” and “Forms API Reference” on http://api.drupal.org/api/7, as well as the hook_form_FORM_ID_alter() docs to learn the full flexibility of Forms API. Note that themes can no longer use the phptemplate_ prefix to the function; you’ll need to use the actual name of your theme as the prefix.
Here’s an example if you had a “foo” theme and wanted to add a textfield whose default value was “blue bikeshed”:
<?php
function foo_form_system_theme_settings_alter(&$form, $form_state) {
$form['caberet_example'] = array(
'#type' => 'textfield',
'#title' => t('Widget'),
'#default_value' => theme_get_setting('foo_example'),
'#description' => t("Place this text in the widget spot on your site."),
);
}
?>In order to set the default value for any form element you add, you’ll need to add a simple line to your .info file: settings[SETTING_NAME] = DEFAULT_VALUE. For our foo theme, you’d need to edit the foo.info file and this line:
settings[foo_example] = blue bikeshedIn any of your theme’s php files, you can retrieve the value the user set by calling:
<?php
$foo_example = theme_get_setting('foo_example');
?>theme_form_required_marker()
(issue) Разметка для геренарции маркеров для обязательных элементов формы теперь управляется отдельной функцией theme_form_required_marker() вместо более общей theme_form_element(). Это позволяет многократно использовать маркер в различных местах или изменять разметку без изменения все функции theme_form_element().
theme_link()
(issue) Разметка для генерации ссылок теперь управляется функцией theme_link(), вместо ранее применявшегося статичного кодирования в функции l(). This allows you to implement a preprocess function or an override function in order to customize the markup of any link. Doing so may slow down Drupal pages that have many links, so it is recommended to evaluate the benefit vs. the performance trade-off, but the capability exists for sites and themes that need it. This theme function is for customizing the markup of links, generically. Other theme functions exist for customizing links based on context. For example, to customize menu links, override theme_menu_link() instead.
hook_preprocess_link():
<?php
function mytheme_preprocess_link(&$variables) {
// In order to style links differently depending on what they are linking to,
// add classes that contain information about the link path.
if (strpos($variables['path'], ':') !== FALSE) {
// For external links, add a class indicating an external link and a class
// indicating the scheme (e.g., for 'mailto:...' links, add a 'link-mailto'
// class).
$variables['options']['attributes']['class'][] = 'link-external';
$variables['options']['attributes']['class'][] = 'link-' . parse_url($variables['path'], PHP_URL_SCHEME);
}
else {
// For internal paths, add a class indicating an internal link.
$variables['options']['attributes']['class'][] = 'link-internal';
if (empty($variables['path']) || $variables['path'] == '<front>') {
// Add a class indicating a link to the front page.
$variables['options']['attributes']['class'][] = 'link-front';
}
else {
// For internal links not to the front page, add a class for each part
// of the path. For example, for a link to 'admin/structure/block', add
// the classes 'link-path-admin', 'link-path-admin-structure', and
// 'link-path-admin-structure-block'.
$class = 'link-path';
foreach (explode('/', $variables['path']) as $path_part) {
$class .= '-' . $path_part;
$variables['options']['attributes']['class'][] = $class;
}
}
}
}
?>overriding theme_link():
<?php
function mytheme_link($variables) {
// Place a span within and outside the anchor tag in order to implement some
// special styling.
return '<span class="link-wrapper"><a href="' . check_plain(url($path, $options)) . '"' . drupal_attributes($options['attributes']) . '><span class="link-content-wrapper">' . ($options['html'] ? $text : check_plain($text)) . '</span></a></span>';
}
?>Skip to main content links in core themes
(issue) To meet Web Content Accessibility Guidelines (WCAG) 2.0 guideline 2.4.1 Bypass Blocks, web pages need to have a link to help keyboard only users and screen readers more easily access the main content of a website.
Garland's implementation is hidden visually, but keep them available for screen-readers. Furthermore, if a keyboard only user tabs through a site the link will become visible as it gains focus.
To hide the skip navigation you can use one the new classes available to hide content in an accessible manner.
Alter hooks available to themes
(Issue) Hooks that are used to alter content before being displayed on the page are now available to themes. Some important ones to note are:
Note that although technically all of the alter hooks are exposed to the theme, only a given number of them will actually work due to the way the Drupal bootstrap works. If you need to use hook_menu_alter, for example, you'll have to use a module. These hooks can be exposed in template.php.
Drupal 7.x:
<?php
/**
* Implement hook_page_alter().
*/
function mytheme_page_alter(&$page) {
// Remove elements from the page.
}
/**
* Implement hook_css_alter().
*/
function mytheme_css_alter(&$css) {
// Replace some CSS files with this theme's special CSS.
}
?>Изменены стили модуля System
(Issue) Стили, которые связаны с определённым поведением отделены от общих стилей.
- Стили файлов default.css и system.css объединены вместе в файле system.css. Файл default.css удалён.
- Был добавлен файл system-behavior.css, который определяет оформление элементов связанных с определёнными действиями, например автозавершением, перетаскиванием пунктов мышкой, прогресс-баром и т.д.
Темам добавлен параметр, определяющий вывод значков для добавления ярлыка страницы
(issue) В Drupal 7, при включенном модуле Shortcut, стандартная тема Seven добавляет значки +/– к заголовкам страниц (если у пользователя есть соответствующие права), что позволяет быстро добавлять ярлык этой страницы.
Видимость этих значков определяется параметрами темы. Если вы хотите, чтобы эти значки показывались при включении модуля Shortcut, то в .info-файл темы нужно добавить следующий код:
settings[shortcut_module_link] = 1Для перекрытия шаблонов используются два дефиса вместо одного
(issue) В Drupal 6, шаблоны могли быть целенаправленно перекрыты. Например, тема могла содержать шаблон node-article.tpl.php, который использовался только для типа документов article. В Drupal 7, необходимо будет переименовать такой шаблон с использованием в его названии двух дефисов, т.е. в node--article.tpl.php. Один дефис по-прежнему используется для разделения слов, например user-picture.tpl.php или node--long-content-type-name.tpl.php. Таким образом, два дефиса в названии шаблона всегда говорят о целенаправленном перекрытии, а не просто о разделении слов дефисами.
Если ваша тема использует функции препроцесса, посмотрите страницу http://drupal.org/update/modules/6/7#theme_hook_suggestions_2, на которой рассказано как это изменение затронет вашу тему.
CSS-файлы иногда загружаются через @import, иногда через LINK
(issue) До Drupal 6, CSS-файлы обычно добавлялись на страницу с использованием оператора @import внутри тегов STYLE. Drupal 6 стал использовать тег LINK. В Drupal 7, теги LINK используются в случае включения параметра «Собирать и сжимать все CSS-файлы в один файл», но оператор @import иногда используется и когда этот параметр выключен. Необходимость этого вызвана ограничением браузера Internet Explorer на количество загружаемых файлов, т.к. он может загрузить только первые 31 тег, которые добавляют CSS-файлы. Информацию о том, когда используются теги LINK и когда операторы @import, можно найти в документации по API, на странице drupal_pre_render_styles().
CSS-файлы для определённых браузеров добавляются с использованием drupal_add_css()
(issue) Drupal 7 предоставляет возможность определить ключи для браузеров при использовании drupal_add_css().
Drupal 6
template.php:
<?php
...
function phptemplate_get_ie_styles() {
global $language;
$iecss = '<link type="text/css" rel="stylesheet" media="all" href="'. base_path() . path_to_theme() .'/fix-ie.css" />';
if ($language->direction == LANGUAGE_RTL) {
$iecss .= '<style type="text/css" media="all">@import "'. base_path() . path_to_theme() .'/fix-ie-rtl.css";</style>';
}
return $iecss;
}
...
?>page.tpl.php:
<?php
...
<?php print $styles ? >
<!--[if lt IE 7]>
<?php print phptemplate_get_ie_styles(); ? >
<![endif]-->
...
?>Drupal 7
template.php:
<?php
...
function garland_preprocess_html(&$vars) {
...
drupal_add_css(path_to_theme() . '/fix-ie.css', array('weight' => CSS_THEME, 'browsers' => array('IE' => 'lt IE 7', '!IE' => FALSE), 'preprocess' => FALSE));
}
...
?>Подробную информацию о ключах IE и !IE, см. в документации по API на странице drupal_pre_render_conditional_comments().
Рекомендуется всегда использовать drupal_add_css() для добавления CSS-файлов, т.к. это позволяет знать точное количество добавляемых файлов. Эта информация может быть важна при работе с Internet Expolore и связана с ограничениями этого браузера, который позволяет загружать только первый 31 тег LINK/STYLE.


