tera
tera copied to clipboard
global context/variables
I have looked through tera and i can't find a way to add global context/variables to tera.
In twig, you can add a global context that will be provided in every template, unless overridden by later context.
To give an example:
<?php
use Twig;
$loader = new Twig\Loader\ArrayLoader([
'example.html.twig' => '<p>The Google tracking code is: {{ ga_tracking }}</p>'
]);
$twig = new Twig\Environment($loader);
$twig->addGlobal('ga_tracking', 'xxxxx');
$a = $twig->render('example.html.twig', []);
// $a = "<p>The Google tracking code is: xxxxx</p>"
$b = $twig->render('example.html.twig', ['ga_tracking' => 'yyyyy']);
// $b = "<p>The Google tracking code is: yyyyy</p>"
This feature is useful when you want to inject some variables in the application that could be changed from time to time, without having to hard code them in the template, as they could live in a configuration file, and be injected into tera to be available globally to all templates.
ref: https://symfony.com/doc/current/templating/global_variables.html
my question: is there a way to achieve this in tera? I know that i can add a function that would return the value, but was wondering whether it is possible to have global variables pre-set, as it allows for them to be overridden if needed.
It's not possible in Tera outside of a function as you mentioned
@Keats thanks, would you accept a PR to implement this? or is there a reason not to?
I'm not adding any new big features to Tera right now. I'll add that as consideration for the next major version though