Theming

Last updated on
21 September 2016

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 ditch the .module file is because that's where hook_theme() goes. This one works pretty much like in D7: you 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. The following hook inserts random punctuation at the end of each sentence:

/**
 * Template preprocess function for Lorem ipsum
 *
 * @param 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, surrounded by <p> tags.

Notice the correspondence between hook_theme(), template_preprocess_hook() and our Twig file:

hook_theme() variable
template_preprocess_hook() variable
twig variable