Darius Leskauskas
Darius Leskauskas

Reputation: 63

renderFile do not load custom Twig extensions

I'm trying to create my own Generator, using SensioGeneratorBundle as a core. But there is a problem with custom Twig extensions loading. If I use

return $this->container->get('templating')->renderResponse('Acme:Generator/Work:edit.html.twig', array());

extension is working, but if I use

return $this->renderFile('edit.html.twig', array('entity' => $entity));

where

protected function renderFile($template, $parameters)
{
    $twig = new \Twig_Environment(new \Twig_Loader_Filesystem($this->skeletonDirs), array(
        'debug'            => true,
        'autoReload'       => true,
        'cache'            => false,
        'strict_variables' => true,
        'autoescape'       => true,
    ));

    return $twig->render($template, $parameters);
}

Only core Twig extensions are loaded. And I get an error

The filter "price" does not exist in edit.html.twig at line 9

Any ideas?

Upvotes: 1

Views: 424

Answers (1)

Žilvinas Kuusas
Žilvinas Kuusas

Reputation: 46

SensioGeneratorBundle creates it's own Twig instance in renderFile() method you gave, and it doesn't have anything in common with Twig instance loaded into Symfony's service container, which is being used by calling $this->container->get('templating')->renderResponse().

And you can't use Twig instance from service container here, because it has some behaviours which could break Sensio's skeleton rendering. So the new Twig Environment instance is created on purpose in renderFile() method.

You need to add filters manually to newly created Twig Environment instance in renderFile() method, as simple as:

$twig->addFilter($filter);

About Twig filters: http://twig.sensiolabs.org/doc/advanced.html#filters

Upvotes: 2

Related Questions