How to define global variable for Twig

2019-02-09 07:56发布

问题:

I'm using a file serving as a form layout to overwrite certain elements (form_start, form_row, etc.). I register it like:

twig:
    - AcmeMainBundle:Form:formlayout.html.twig

Is there a way to use in it my variables provided along with a form?

For example, when I send to index.html.twig

array ('form' => $formView, 'var' => $var);

Var is defined only in index.html.twig.

So how to make var defined in formlayout.html.twig

回答1:

You can use addGlobal() method.

For example in BaseController I use:

$this->get('twig')->addGlobal('is_test', $isTest);

so in your case you should probably do:

$this->get('twig')->addGlobal('var', $var);


回答2:

To set a global variable in Twig I created a service call "@get_available_languages" (return an array) and then on my kernel.request event class I implemented the below:

  class LocaleListener implements EventSubscriberInterface
{
    private $defaultLocale;

    public function __construct($defaultLocale = 'en',       ContainerInterface $container)
    {
        $this->defaultLocale = $defaultLocale;
        $this->container = $container;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        //Add twig global variables
        $this->addTwigGlobals();


    }



    public function addTwigGlobals(){

        //Add avaialble language to twig template as a global variable
        $this->container->get('twig')->addGlobal('available_languages', $this->container->get('get_available_languages'));

    }

    public static function getSubscribedEvents()
    {
        return array(
            // must be registered before the default Locale listener
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
        );
    }
}

Hope that helps

Peace



回答3:

In case you don't use symphony but use twig on it's own, it is as simple as:

<?php

$loader = new \Twig_Loader_Filesystem('path/to/templates');
$twig = new \Twig_Environment($loader);
$twig->addGlobal('key1', 'var1');
$twig->addGlobal('key2', 'var2');


标签: php symfony twig