Rob MacGregor
Rob MacGregor

Reputation: 11

Symfony2 Twig: url /path functions do not exist when loading templates with custom loader

I wrote a custom DatabaseTwigLoader, based on this recipe: http://twig.sensiolabs.org/doc/recipes.html#using-a-database-to-store-templates

It works fine. I am using this loader to load email templates from the DB, render them and send them using swift mailer.

The problem is, when rendering the templates, I can't use the path or the url twig functions. The error returned is:

The function "path" does not exist in "NEW_POST_ON_YOUR_GOAL" at line 6 (500 Internal Server Error)

However, variable interpolation and filters are applied and template inheritance works.

Do I need to register the url / path functions with the custom loader? Is it something to do with these functions being dependant on routing?

Thanks in advance.

** The implementation of the solution as suggested by @MolecularMan **

I had to add the routing extension to the twigEnvironment. I did this using the TwigEnvironment::addExtension() method.

In order to achieve this using DI, I had to extend the urlGenerator class (passed as the constructor argument to the routing_extension service).

The UrlGenerator takes a routeCollection object as a constructor argument. So I pass the router service as a constructor argument to my extended urlGenerator, so that I can extract the routecollection and pass it to parent::__contruct()

In order to achieve this using DI, I had to extend the urlGenerator class (passed as the constructor argument to the routing_extension service).

The UrlGenerator takes a routeCollection object as a constructor argument. So I pass the router service as a constructor argument to my extended urlGenerator, so that I can extract the routecollection and pass it to parent::__contruct()

My services.yml file looks like this:

twig_db:
    class: %twig.class%
    arguments: [@twig_db_loader]
    calls: [[ addExtension, [@routing_extension] ]]
url_generator:
    class: ZT\UserBundle\Services\UrlGenerator
    arguments: [@router, @request_context, @logger]
request_context:
    class: Symfony\Component\Routing\RequestContext
routing_extension:
    class: Symfony\Bridge\Twig\Extension\RoutingExtension
    arguments: [@url_generator]
twig_db_loader:
    class: ZT\UserBundle\Services\DatabaseTwigLoader
    arguments: [@doctrine.orm.entity_manager]

Upvotes: 1

Views: 1644

Answers (1)

pliashkou
pliashkou

Reputation: 4130

You should register RoutingExtension:

$loader = new \Twig_Loader_Filesystem(array(__DIR__ . '/../../Resources/views'));
$twig = new \Twig_Environment($loader);

$twig->addExtension(new RoutingExtension($this->getMock('Symfony\Component\Routing\Generator\UrlGeneratorInterface')));
$twig->render('your_view.html.twig');

Upvotes: 0

Related Questions