4
votes

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

3

3 Answers

5
votes

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

3
votes

Try this inside config.yml:

twig:
    # ...
    globals:
        global_var: %client_name%'

And in your twig, u can access it easily:

<p>{{ global_var }}</p>

Also you can try referencing services. See the documentation http://symfony.com/doc/2.8/cookbook/templating/global_variables.html#referencing-services

3
votes

Adding an answer for cases when Twig is used standalone (i.e. when the rest of the project is not built on Symfony).

extension sample

class CustomTwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface
{
    private $globals;

    public function __construct(array $globals) {
        $this->globals = $globals;
    }

    public function getGlobals() {
        return $this->globals;
    }
}

configuring twig:

// where twig is created
$loader = new Twig_Loader_Filesystem('/path/to/templates'); // or whatever loader you would use
$globals = ['global_var' => 'whatever'];
$globalsExtension = new CustomTwigExtension($globals);
$twig = new Twig_Environment($loader);
$twig->addExtension($globalsExtension);

in template:

<div>{{ global_var }}</div>

reference to Twig docs on the topic