Search code examples
phpsymfonytwigtwig-extension

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?
  }
}

Solution

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

    new \Twig_SimpleFunction('myfunc', [$this, '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 function myfunc(\Twig_Environment $env, $context, $name)
    {
         var_dump($context);
    }