处理 URL 参数上的斜杠

2022-01-22 00:00:00 urlencode url-routing php symfony twig

I'm running into some issues trying to guess how to handle URLs with parameters on Symfony+Twig.

I have this route:

<route id="artist.front" path="/artist/{kw}/">
<default key="_controller">AppWebControllersFront::homePage</default>
</route>

And this code on the Twig template:

{% autoescape false %}
<a href="{{ path('artist.front',{'kw':a.urlkeyword|url_encode} )}}">{{ a.name }}</a>
{% endautoescape %}

urlkeyword parameter is passed as is (i.e. not URL encoded previously) both on the entity constructor and on its getter (getURLKeyword).

However, when rendering the template I get this HTML code:

<a href="/index.php/artist/AC%252FDC/">AC/DC</a>

(If I remove the url_encode from the template Twig throws an error calling path()).

The target controller has this code:

public function artistPage($kw)
{
    $decoded = urldecode($kw);
    $this->log->info("kw:      {$kw}");
    $this->log->info("decoded: {$decoded}");
}

and echoes:

kw:      AC%2FDC 
decoded: AC/DC 

so I think the kw is read correctly from the controller, but I understand the URL should be encoded as AC%2FDC instead on the final HTML code on the first place: The URLEncoded string is encoded twice.

Is AC%2FDC the correct encoding, or is it necessary to use the double encoding (AC%252FDC) in Symfony? And, if it is possible to use the first (correct) URL encoding, what I am doing wrong?

解决方案

try:

<route id="artist.front" path="/artist/{kw}/">
    <default key="_controller">AppWebControllersFront::homePage</default>
    <requirement key="kw">.+</requirement>
</route>

And remove the url encoding/decoding.

相关文章