Like @DarkBee mentioned in his comment, you can change the context by passing it via the link:
function setContextVar(&$context, ...)
However, adding only the Twig function does not work (I am using Twig 2.4.4):
$twig->addFunction(new Twig_Function('setContextVar', function(&$context, $name, $value) { $context[$name] = $value; }, ['needs_context' => true]));
When you use a function in a Twig file, the context does not change, and you get this warning:
A warning. Parameter 1 - {closure} () is expected as a link, the value is given in C: \ ... \ vendor \ twig \ twig \ lib \ Twig \ Environment.php (378): eval () 'd code on line ...
Instead, you need to create a Twig extension:
$twig->addExtension(new class extends Twig_Extension { public function getFunctions() { return [ new Twig_Function('setContextVar', [$this, 'setContextVar'], ['needs_context' => true]), ]; } public function setContextVar(&$context, $name, $value) { $context[$name] = $value; } });
Then you can use it in Twig without warning:
{{ dump() }} {% do setContextVar('foo', 'bar') %} {{ dump() }}
The above prints, for example:
array(0) { } array(1) { ["foo"]=> string(3) "bar" }