滚动
在 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 一样:你声明一个数组,包含你的变量和模板文件,这个模板文件必须保存在正确的位置(templates 文件夹)并以 .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 数组通过 Twig 模板中的一个简单 for 循环进行处理,并包裹在 <p> 标签内。
注意 hook_theme()、template_preprocess_hook() 和 Twig 文件之间的对应关系:


