Hinzufügen einer Thematisierungsvorlage zu einem Drupal-Modul
Teil III aus dem praktischen Leitfaden zur Erstellung grundlegender Drupal 8-Module
Von .info zu Tests, nur die Grundlagen
loremipsum.module
/**
* Implementiert hook_theme().
*/
function loremipsum_theme($existing, $type, $theme, $path) {
$variables = array(
'loremipsum' => array(
'variables' => array(
'source_text' => NULL,
),
'template' => 'loremipsum',
),
);
return $variables;
}
Ein weiterer Grund, die .module-Datei nicht aufzugeben, ist, dass genau dort hook_theme() platziert wird. Es funktioniert fast genauso wie in D7: Sie deklarieren ein Array, das Ihre Variablen und die Template-Datei enthält, die am richtigen Ort (im Template-Ordner) mit der Endung .html.twig gespeichert sein muss.
Dann können Sie, bevor Sie das Render-Array an Twig übergeben, eine gewisse Vorverarbeitung durchführen. Der folgende Hook fügt am Ende jedes Satzes zufällige Satzzeichen ein:
/**
* Template-Preprocess-Funktion für Lorem ipsum.
*
* @param array $variables
* Ein assoziatives Array, das enthält:
* - 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
* Standard-Theme-Implementierung zur Ausgabe von Lorem-ipsum-Text.
*
* Verfügbare Variablen:
* - source_text
*
* @see template_preprocess_loremipsum()
*
* @ingroup themeable
*/
#}
<div class="loremipsum">
{% for item in source_text %}
<p>{{ item }}</p>
{% endfor %}
</div>
Jetzt wird das Array $source_text mit einer einfachen for-Schleife innerhalb unseres Blocks verarbeitet, der von <p>-Tags umgeben ist.
Achten Sie auf die Übereinstimmung zwischen hook_theme(), template_preprocess_hook() und unserer Twig-Datei:


