Twig in Drupal
Drupal 8+ usa Twig come template engine per il theming, sostituendo il vecchio PHPTemplate. Twig offre sintassi pulita, sandbox di sicurezza, ereditarieta', filtri/funzioni built-in e un'ecosistema condiviso con Symfony.
Anatomia di un theme
Un tema custom in themes/custom/mytheme/ richiede:
mytheme.info.yml mytheme.libraries.yml mytheme.breakpoints.yml templates/ css/ js/ logo.svg screenshot.png
info.yml
name: My Theme type: theme base theme: olivero core_version_requirement: ^10 || ^11 libraries: - mytheme/global regions: header: Header content: Content sidebar: Sidebar footer: Footer
Twig basics
Sintassi:
{{ variable }}: stampa{% if x %}...{% endif %}: condizioni{% for item in items %}...{% endfor %}: cicli{# commento #}: commenti{{ variable|filter }}: filtri
Template hierarchy
Drupal cerca i template più specifici prima dei generici:
node--article--full.html.twig node--article.html.twig node--full.html.twig node.html.twig
Suggestions visibili con Twig debug ON (in services.yml di sviluppo).
Variabili comuni
In node.html.twig:
{{ content }}: l'intero contenuto renderizzato{{ content.field_image }}: singolo campo{{ label }}: titolo del nodo{{ node.id }}: oggetto nodo accessibile{{ url }}: URL del nodo
Filtri utili
|t: traduzione|raw: output senza escape (usare con cautela)|safe_join: array a stringa|trim: rimuove whitespace|format_date: formatta data|without('field_x'): rimuove un campo dal render
Attach library
Per caricare CSS/JS solo dove serve:
{{ attach_library('mytheme/component-hero') }}Single Directory Components (SDC)
Drupal 10.1+ include SDC: ogni component vive in una cartella con .twig, .yml (props/slots), .css, .js. Esempio:
components/card/ card.component.yml card.twig card.css card.js
Si include con {{ include('mytheme:card', {title: 'Hello'}) }}.
Debug
In sites/default/services.yml abilitare:
twig.config: debug: true auto_reload: true cache: false
Mostra commenti HTML con suggestions e file source di ogni template.
Hai bisogno di aiuto?
Se vuoi un sito Drupal performante dal team di G Tech Group, scrivici tramite il modulo di contatto.