Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templating with Twig - permanent access to a variable in all my templates

I've just started looking into Twig and I'm wondering how I would accomplish the following.

I have a variable $logged_in that I need to have access to in every single page on my site, I was hoping that rather than passing this to the twig renderer every single time in the data array, there would be a way for me to declare this somewhere, and for every template to have access to it.

Do I need to build an extension to accomplish this / or is it even possible? I have looked through every page of the documentation but I'm having trouble having tried to extend the base template as described here...

Twig Documentation | Recipes | Making the Templates aware of the Context Dead link

Is this the right approach?

Thanks

like image 502
calumbrodie Avatar asked Oct 21 '10 17:10

calumbrodie


People also ask

How do I add a global variable in Twig?

If you are using Twig in another project, you can set your globals directly in the environment: $twig = new Twig_Environment($loader); $twig->addGlobal('myStuff', $someVariable); And then use {{ myStuff }} anywhere in your application.

How do you set a variable in Twig template?

This can be accomplished by creating an array of the entry years. Inside the loop that's building the array, a conditional checks if the year already exists in the array... if the year exists, a variable is set to TRUE which you can use in your conditional later down on the page. Save this answer.

What is raw in Twig?

3. raw. By default, everything in Twig gets escaped when automatic escaping is enabled. If you don't want to escape a variable you'll have to explicitly mark it as safe which you can do by using the raw filter.


1 Answers

Just read about the new features in the 1.0RC release which should help.

Taken from the blogpost:

Globals:

PHP

// a global can be a constant
$twig->addGlobal('pi', 3.14);

// or any other valid PHP expression, like an object
$twig->addGlobal('request', new Request());

Template

{{ pi }}

{{ request.params('name') }}
like image 104
Les Avatar answered Sep 22 '22 07:09

Les