tera icon indicating copy to clipboard operation
tera copied to clipboard

global context/variables

Open azjezz opened this issue 2 years ago • 3 comments

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.

azjezz avatar Oct 19 '22 21:10 azjezz

It's not possible in Tera outside of a function as you mentioned

Keats avatar Oct 20 '22 11:10 Keats

@Keats thanks, would you accept a PR to implement this? or is there a reason not to?

azjezz avatar Oct 20 '22 11:10 azjezz

I'm not adding any new big features to Tera right now. I'll add that as consideration for the next major version though

Keats avatar Oct 20 '22 12:10 Keats