I have code like this in the base controller:
$this->eu_cookie_preference = $this->input->cookie('eu-cookie-preference');
and in each one of my controller functions I pass this variable to the twig like this:
$this->twig->display('account/my_details.twig', array(
'title' => 'Website | My Details',
'lang' => $this->lang,
'eu_cookie_preference' => $this->eu_cookie_preference,
));
And in the Base Twig I use this variable to do various things. Is there a way to access the $this->eu_cookie_preference variable from Twig without having to explicitly pass it to each Twig in every controller function?
I have a similar problem with session vars as I have to pass them to each twig in order to access them.
Answer
You can use Twigs
addGlobal
function to do so. See manualYou can use these globals just like normal vars:
Additional information
This way you can implement lazy loading as well. If you load sessions data from your database, that will not be used in every template it can be useful to build a class like this:
and pass values like this:
The function will only be called, when you call the variable in twig.