Search code examples
phpsymfonydecoratorroutersymfony5

Change Twig url() output in Symfony


What is the file/class that ultimately executes the Twig url() function, like here: <a href="{{ url('app_home') }}">Home</a> in twig.

I know I can use a decorator to change functions with something like:

App\Services\MyRouter:
    decorates: 'router'
    arguments: ['@App\Services\MyRouter.inner']

and

public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH)
{
    $name = 'test'.$name;

    return $this->router->generate($name, $parameters, $referenceType);
}

The above changes the route which affects other areas like loading controllers.

All I'm after is the final output in the twig document. I haven't been able to find the the correct service to decorate.

edit

Based off the answers I have been working with twig.extension.routing but now I just get an "Unknown "path" function." exception. My expectation would be for nothing to happen and my function returns the original method.

App\Service\TwigUrlDecorator:
    decorates: 'twig.extension.routing'
    arguments: ['@App\Service\TwigUrlDecorator.inner']
    public: false

<?php
// src/Service/TwigUrlDecorator.php

namespace App\Service;

use Twig\Extension\AbstractExtension;

class TwigUrlDecorator extends AbstractExtension
{

    public function getPath($name, $parameters = array(), $relative = false)
    {
        return parent::getPath($name, $parameters, $relative);
    }

}

Solution

  • The url twig function is executed by Symfony\Bridge\Twig\Extension\RoutingExtension::getUrl().

    You can find the class definition here, and the specific method here. The service is defined here, where you can see the service name is twig.extension.routing.

    I guess you could decorate the extension, but considering how simple it is, it might be simpler just to define your own URL generating twig function by defining a new Twig Extension.