How can i create the global variable in symfony controller like in laravel (example: view()->share('now', date('Y-m-d')); ), that it availiable in all templates?
-
2Symfony Documentation: How to Inject Variables into all TemplatesKep– Kep2017-10-05 21:25:13 +00:00Commented Oct 5, 2017 at 21:25
-
@ccKep Well answered. Here you have a lot of info related with globals in templates in Docs. Thank youOscar– Oscar2017-10-06 08:11:45 +00:00Commented Oct 6, 2017 at 8:11
3 Answers
Setting a global template variable
It is possible to set a global variable available in every template using the addGlobal function in the BaseController class.
$this->get('twig')->addGlobal('today', date('Y-m-d'));
The Twig date functions
Remember that Twig is at its core simply a templating enging for php; it's a skin, an illusion. It replaces the old style <?php echo date('Y-m-d'); ?> commonly used in php. This means two things:
- Twig statements are executed server-side
- Twig can access (most) php's native function
So in order to set a global variable with today's date, you can imply add the following line:
{% set today = date() %}
If you want to have today be available every template, simply set it in your base.twig.html template. Alternatively you can also use the function only when needed.
2 Comments
one possibility is to create variable in session like this.
$session = $this->get('session');
$session->set('var', $my_variable);
in another controller you just get it like this
$session->get('var');
in twig you can get your variable
{% app.session.get('var') %}
it can resolve your issue and it is avalaible for a user not globally.