2

I need to define a global variable in symfony2 and then, use it in several php template.

I found in documentation how to use in twig templates, but I need how to define and use in php template.

Thanks.

2 Answers 2

2

You can define global variable in twig template like:

# app/config/config.yml
twig:
    # ...
    globals:
        ga_tracking: UA-xxxxx-x

Or it in PHP template like:

// app/config/config.php
$container->loadFromExtension('twig', array(
     // ...
     'globals' => array(
         'ga_tracking' => 'UA-xxxxx-x',
     ),
));

And then use it in twig:

<p>The google tracking code is: {{ ga_tracking }}</p>

or in PHP template:

<p>The google tracking code is: <?php echo $ga_tracking; ?></p>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but this doesn't work because when you said: Or it in PHP template like:... this is tod efine global variable for twig template but using php languaje y config.php instead of YAML like in the first one. But both are for twig template, see that in code is written: 'twig'
Only in PHP template doesn't exist the variable
2

You have to define the variable in your config file, for example:

# app/config/config.yml
parameters:
      foo: "bar"

and then you can access it from your PHP templates:

<?php echo $view->container->parameters['foo']; ?>

3 Comments

Thanks, but I had this and echo doesn't work, I see with debugger and variable doesn't exists
There has to be a problem somewhere in your code, it works for me just fine. Do you have the php templating engine allowed? Have you tried to clear the cache? Are you accessing the right parameter name? Maybe you have set different parameters for prod/dev environment?
Yes thanks, I don't know where is the problem, I'll search in my code, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.