Theming
Last updated on
13 September 2023
loremipsum.module: hook_theme() implementation
/**
* Implements hook_theme().
*/
function loremipsum_theme($existing, $type, $theme, $path) {
$variables = array(
'loremipsum' => array(
'variables' => array(
'source_text' => NULL,
),
'template' => 'loremipsum',
),
);
return $variables;
}
The .module file houses an implementation of hook_theme(). Declare an array containing your variables and template file, which should be saved in the correct location (the templates folder) with the .html.twig extension.
Then, right before handing your render array over to Twig, you can do some preprocessing - we'll basically change the output. The following hook inserts random punctuation at the end of each sentence, which isn't defined anywhere else:
/**
* Template preprocess function for Lorem ipsum
*
* @param variables
* An associative array containing:
* - source_text
*/
function template_preprocess_loremipsum(&$variables) {
// Defines a list of acceptable punctuation.
$punctuation = array('. ', '! ', '? ', '... ', ': ', '; ');
// Loops over text, one paragraph at a time, taking it apart
// and gluing it back together with random punctuation.
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>The last step in the visual presentation is where the $source_text array is processed using a simple for loop inside our twig, surrounded by <p> tags.
Notice the correspondence between hook_theme(), template_preprocess_hook() and our Twig file:
function loremipsum_theme($existing, $type, $theme, $path) {$variables = array('loremipsum' => array('variables' => array('source_text' => NULL,function template_preprocess_loremipsum(&$variables) {(...)$variables['source_text'][$i] = implode('', $big_text);{% for item in source_text %}<p>{{ item }}</p>{% endfor %}Help improve this page
Page status: No known problems
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion