How to define global variable for Twig

后端 未结 3 686
死守一世寂寞
死守一世寂寞 2020-12-16 01:33

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

twig:
    - Acme         


        
相关标签:
3条回答
  • 2020-12-16 02:12

    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)),
            );
        }
    }
    
    0 讨论(0)
  • 2020-12-16 02:28

    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);
    
    0 讨论(0)
  • 2020-12-16 02:33

    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');
    
    0 讨论(0)
提交回复
热议问题