Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render template from twig extension

I have built a twig extension to do some things and one of them is render a template. How can I access from inside the twig extension the engine environment and call the Render method?

like image 306
Stefano Avatar asked Mar 03 '12 19:03

Stefano


1 Answers

You can define the extension so that it needs the environment. Twig will automatically pass it to the function.

use Twig\Environment;
use Twig\TwigFunction;

public function getFunctions()
{
    return [
        new TwigFunction(
            'myfunction',
            [$this, 'myFunction'],
            ['needs_environment' => true]
        ),
    ];
}

public function myFunction(Environment $environment, string $someParam)
{
    // ...
}

For older versions of Twig

public function getFunctions()
{
    return array(
        new \Twig_SimpleFunction(
            'myfunction',
            array($this, 'myFunction'),
            array('needs_environment' => true)
        ),
    );
}

public function myFunction(\Twig_Environment $environment, string $someParam)
{
    // ...
}
like image 85
tvlooy Avatar answered Oct 19 '22 12:10

tvlooy