It’s possible to generate a URL from within a Twig extension in a Symfony2 application. To do this, you need to have access to the Router. If you have a custom Twig extension, this means that you’ll need to inject the router to the extension. Thanks to the Dependency Injection this is very easy to do.

First, edit your services configuration to inject the Router:

  <service id="name.twig.extension" class="YourNamespaceTwigExtension">
    <tag name="twig.extension" />
    <argument type="service" id="router"/>

The important part here is that you add the <argument type=”service” id=”router”/> line for your extension.

Then, modify your Twig extension class to receive and store the Router:

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class TwigExtension extends \Twig_Extension
  private $generator;

  public function __construct(UrlGeneratorInterface $generator)
    $this->generator = $generator;

Now, in your filter method you can generate the URL easily:

$url = $this->generator->generate('route', array('userId' => $user->getId()));

You can also view the TwigBridge source code for inspiration on how is done in Symfony2.