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
In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state.
Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
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');
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)),
);
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With