Creative Commons License
This work is licensed under a
Creative Commons
Attribution-Share Alike 3.0
Unported License.

Master Symfony2 fundamentals

Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).
trainings.sensiolabs.com

Symfony hosting done right

ServerGrove, outstanding support at the right price for your Symfony hosting needs.
servergrove.com

Discover the SensioLabs Support

Access to the SensioLabs Competency Center for an exclusive and tailor-made support on Symfony
sensiolabs.com

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.