Search code examples
phptwigsymfony3

Encoding parameters in Symfony path twig function


In my application, I'm using the Symfony Twig extension function path to create a link to another route. That route accepts a parameter, so I wrote my path function like this:

<a href="{{ path('r', {p: p}) }}">...</a>

In some cases, the given value p contains a slash and Symfony fails with the error:

"Parameter "p" for route "r" must match "[^/]++" (".../..." given) to generate a corresponding URL.")

I would expect Symfony to deal with this and automatically URL encode these values, but apparently not (or I'm doing something wrong).

Anyway, I managed to fix that with the url_encode Twig filter, like so:

<a href="{{ path('r', {p: p|url_encode}) }}">...</a>

Now in my controller, I accept this parameter like so:

/**
 * @Route("/a/b/{p}", name="r")
 **/
public function someAction($p) {
   // ...
}

And apparently Symfony does not automatically URL decode this value $p, which I'd expect as well.

Am I doing something wrong here, or is it really necessary to handle URL encoding/decoding yourself? In the Symfony docs I don't find any details about this at all.


Solution

  • Apparently the default parameter restrictions don't allow forward slashes. After "loosening" them it worked:

    /**
     * @Route("/a/b/{p}", name="r", requirements={"diagramResourceId"=".+"})
     **/
    public function someAction($p) {
       // ...
    }