Table of Contents
Questions & Feedback
Found a typo or an error?
Want to improve this document? Edit it.
Need support or have a technical question?
Post to the user mailing-list.
Master Symfony2 fundamentals
Symfony hosting done right
Discover the SensioLabs Support
Iniettare variabili in tutti i template (variabili globali)
Iniettare variabili in tutti i template (variabili globali)¶
A volte si vuole che una variabile sia accessibile in tutti i template usati.
Lo si può fare, modificando il file app/config/config.yml:
- YAML
1 2 3 4 5
# app/config/config.yml twig: # ... globals: ga_tracking: UA-xxxxx-x
- XML
<!-- app/config/config.xml --> <twig:config ...> <!-- ... --> <twig:global key="ga_tracking">UA-xxxxx-x</twig:global> </twig:config> - PHP
1 2 3 4 5 6 7
// app/config/config.php $container->loadFromExtension('twig', array( // ... 'globals' => array( 'ga_tracking' => 'UA-xxxxx-x', ), ));
Ora, la variabile ga_tracking è disponibile in tutti i template Twig
1 | <p>Il codice di tracciamento Google è: {{ ga_tracking }} </p>
|
È molto facile! Si può anche usare il sistema I parametri del servizio, che consente di isolare o riutilizzare il valore:
1 2 3 | # app/config/parameters.yml
parameters:
ga_tracking: UA-xxxxx-x
|
- YAML
1 2 3 4
# app/config/config.yml twig: globals: ga_tracking: "%ga_tracking%"
- XML
<!-- app/config/config.xml --> <twig:config ...> <twig:global key="ga_tracking">%ga_tracking%</twig:global> </twig:config> - PHP
1 2 3 4 5 6
// app/config/config.php $container->loadFromExtension('twig', array( 'globals' => array( 'ga_tracking' => '%ga_tracking%', ), ));
La stessa variabile è disponibile esattamente come prima.
Variabili globali più complesse¶
Se la variabile globale che si vuole impostare è più complicata, per esempio un oggetto,
non si potrà usare il metodo precedente. Invece, occorrerà creare
un'estensione Twig e restituire la
variabile globale come una delle voci del metodo getGlobals.





is a trademark of Fabien Potencier. All rights reserved.