logo

Extra Block Types (EBT) - Nuova esperienza con Layout Builder❗

Extra Block Types (EBT) - tipi di blocchi stilizzati e personalizzabili: Slideshows, Tabs, Cards, Accordion e molti altri. Impostazioni integrate per sfondo, DOM Box, plugin javascript. Vivi oggi il futuro della costruzione dei layout.

Demo moduli EBT Scarica moduli EBT

❗Extra Paragraph Types (EPT) - Nuova esperienza con Paragraphs

Extra Paragraph Types (EPT) - insieme di moduli basati su paragrafi in modo analogo.

Demo moduli EPT Scarica moduli EPT

Scorri

Aggiungere un template di tematizzazione in un modulo Drupal

03/10/2025, by Ivan

Menu

Parte III della guida pratica alla creazione di moduli di base in Drupal 8
Dai file .info ai test, solo le basi

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;
}

Un altro motivo per non abbandonare il file .module è che è proprio lì che va hook_theme(). Funziona quasi allo stesso modo di D7: dichiari un array che contiene le tue variabili e il file di template, che deve essere salvato nella posizione corretta (cartella templates) con estensione .html.twig.

Poi, prima di passare l’array di rendering a Twig, puoi eseguire un po’ di preprocess. Il seguente hook inserisce una punteggiatura casuale alla fine di ogni frase:

/**
 * 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>

Ora l’array $source_text viene elaborato con un semplice ciclo for dentro il nostro Twig, racchiuso da tag <p>.

Nota la corrispondenza tra hook_theme(), template_preprocess_hook() e il nostro file Twig:

06_0

07_0

08_0