Adding template in Drupal module for theming
Part III of the practical guide to creating basic Drupal 8 modules
From .info to tests, just the basics
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; }
Another reason not to abandon the .module file is that it’s where hook_theme() goes. It works almost the same as in D7: you define an array containing your variables and the template file, which must be stored in the correct location (the templates folder) with a .html.twig extension.
Then, before passing the render array to Twig, you can perform some preprocessing. The following hook inserts random punctuation at the end of each sentence:
/** * 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>
Now the $source_text array is processed using a simple for loop inside our Twig template, wrapped with <p> tags.
Note the correspondence between hook_theme(), template_preprocess_hook(), and our Twig file:
Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.