Добавление шаблона темизации в модуль Drupal
Часть III из практического руководства по созданию базовых модулей Drupal 8
От .info к тестам, только основы
loremipsum.module
/**
* Implements hook_theme().
*/
function loremipsum_theme($existing, $type, $theme, $path) {
$variables = array(
'loremipsum' => array(
'variables' => array(
'source_text' => NULL,
),
'template' => 'loremipsum',
),
);
return $variables;
}
Другая причина не отказываться от файла .module заключается в том, что именно туда идет hook_theme(). Это работает почти так же, как в D7: вы объявляете массив, содержащий ваши переменные и файл шаблона, который должен быть сохранен в правильном месте (папка с шаблонами) с расширением .html.twig.
Затем, перед передачей массива рендеринга в Twig, вы можете выполнить некоторую предварительную обработку. Следующий хук вставляет случайную пунктуацию в конце каждого предложения:
/**
* Template preprocess function for Lorem ipsum.
*
* @param array $variables
* An associative array containing:
* - source_text
*/
function template_preprocess_loremipsum(&$variables) {
$punctuation = array('. ', '! ', '? ', '... ', ': ', '; ');
for ($i = 0; $i < count($variables['source_text']); $i++) {
$big_text = explode('. ', $variables['source_text'][$i]);
for ($j = 0; $j < count($big_text) - 1; $j++) {
$big_text[$j] .= $punctuation[floor(mt_rand(0, count($punctuation) - 1))];
}
$variables['source_text'][$i] = implode('', $big_text);
}
}
/templates/loremipsum.html.twig
{#
/**
* @file
* Default theme implementation to print Lorem ipsum text.
*
* Available variables:
* - source_text
*
* @see template_preprocess_loremipsum()
*
* @ingroup themeable
*/
#}
<div class="loremipsum">
{% for item in source_text %}
<p>{{ item }}</p>
{% endfor %}
</div>
Теперь массив $source_text обрабатывается с помощью простого цикла for внутри нашей ветки, окруженного тегами <p>.
Обратите внимание на соответствие между hook_theme(), template_preprocess_hook() и нашим файлом Twig:


