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
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.
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.
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.
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') }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With