Robert Labrie Robert Labrie - 2 months ago 25
Twig Question

php twig get variables passed to render in extension function

I swear I've googled this and tried to understand the docs, but I'm just not getting it. I'm writing a twig function, what I can't understand is how I can access the variables passed into render from inside the function.

So if I have this registering my extension and calling render:

$o = new SomeObject();
$twig->addExtension(new MyExtension());
$twig->render('example.html',array('obj'=>$o))


And example.html is just
{{ myfunc('foo') }}

How can I access the variable 'obj' from inside myfunc in MyExtension:

class MyExtension extends \Twig_Extension
{
public function getName()
{
return 'myextension';
}
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('myfunc', 'MyExtension::myfunc', array('needs_environment' => true))
);
}
public static function myfunc(\Twig_Environment $env, $name)
{
//how to I get 'obj' from $twig->render in here?
}
}

Answer

You want to use 'needs_context' => true on the function declaration:

new \Twig_SimpleFunction('myfunc', 'MyExtension::myfunc', [
    'needs_environment' => true,
    'needs_context' => true,
])

You'll then get, as a first (or second if needs_environment is also true) argument, an array with data of the current context. This will hold your variables.

public static function myfunc(\Twig_Environment $env, $context, $name)
{
     var_dump($context);
}

Note: If you don't have a very good reason, don't make the function static.

Comments