Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set global variables in Twig using symfony2

Tags:

symfony

I'm using symfony 2.8 and twig 1.2, I was wondering if there is a way to set a global variable for twig templates, I would hate to go into each and every twig file and change the value, if there was a central place where I can set the variable value and use it in any of the twig files regardless of the directories they are in that would be great.

As of now I'm defining key values in parameters.yml file

parameters:
    client_name: 'naruto uzumaki'

And then inside the controller I have

<?php
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class MyController extends Controller
{
    public function editAction()
    {
        $var = $this->container->getParameter('client_name');
        return $this->render("UserBundle:edit:edit.html.twig", array('var' => $var));
    }
}

Then displaying it inside twig,

<h1>Hello, {{ var }}</h1>

I would like to avoid calling the service container in the controller and directly access client_name value in the twig file, any help would be appreciated

like image 623
user5212263 Avatar asked Dec 18 '22 15:12

user5212263


1 Answers

Yes you can, in your config file :

# app/config/config.yml
twig:
    globals:
        my_global_variable: '%client_name%'

Then in Twig :

{{ my_global_variable }}

Don't be scared of searching a solution in google, the first result for 'twig global variable' is :

http://symfony.com/doc/current/cookbook/templating/global_variables.html

like image 176
Alsatian Avatar answered Jan 07 '23 13:01

Alsatian