Dodavanje teme šablona u Drupal modul
Deo III iz praktičnog vodiča za kreiranje osnovnih Drupal 8 modula
Od .info do testova, samo osnove
loremipsum.module
/** * Implementira hook_theme(). */ function loremipsum_theme($existing, $type, $theme, $path) { $variables = array( 'loremipsum' => array( 'variables' => array( 'source_text' => NULL, ), 'template' => 'loremipsum', ), ); return $variables; }
Drugi razlog da ne odustajete od .module fajla je što se upravo tamo nalazi hook_theme(). To funkcioniše skoro isto kao u D7: deklarišete niz koji sadrži vaše promenljive i fajl šablona, koji treba da bude smešten na pravom mestu (folder sa šablonima) sa ekstenzijom .html.twig.
Zatim, pre nego što prosledite niz renderovanju u Twig, možete izvršiti neku prethodnu obradu. Sledeći hook ubacuje nasumičnu interpunkciju na kraj svake rečenice:
/** * Funkcija za prethodnu obradu šablona za Lorem ipsum. * * @param array $variables * Asocijativni niz koji sadrži: * - 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 * Podrazumevana tema za prikaz Lorem ipsum teksta. * * Dostupne promenljive: * - source_text * * @see template_preprocess_loremipsum() * * @ingroup themeable */ #} <div class="loremipsum"> {% for item in source_text %} <p>{{ item }}</p> {% endfor %} </div>
Sada se niz $source_text obrađuje jednostavnom for petljom unutar našeg bloka, okruženog sa <p> tagovima.
Obratite pažnju na podudarnost između hook_theme(), template_preprocess_hook() i našeg Twig fajla:
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.