Render template from twig extension

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)
{
    // ...
}

Using this function the user can pass the twig environment instance to a twig extension

private $environment;

public function initRuntime(\Twig_Environment $environment)
{
    $this->environment = $environment;
}