How to use anchors in Symfony routing?
Asked Answered
C

3

6

I have defined a route as followed in my routing.yml file :

route_name:
    path: "/dashboard#messages/{id}"

However when I ask Symfony to generate that route, I get :

/dashboard%23messages/12345

How can I skip the encoding part of the route generation? Or how can I escape the # char in the path definition?

PS : Working with a (big) legacy system, I cannot change the urls.

Coss answered 28/4, 2016 at 9:40 Comment(0)
C
11

Available from Symfony 3.2.

Support for anchors has been announced for the routing component using the fragment variable :

$this->get('router')->generate('user_settings', ['_fragment' => 'password']);

Will generate an url : /user/settings#password

For more information view the announcement.

Coss answered 6/7, 2016 at 16:1 Comment(1)
With KnpMenuBundle: $node->addChild('settings', ['route' => 'user_settings', 'routeParameters' =>['_fragment' => 'password']])Berhley
N
2

You cannot easily - route parts are encoded unconditionally:

$url = strtr(rawurlencode($url), $this->decodedChars);

see at https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Routing/Generator/UrlGenerator.php#L192

Technically you might have extended the class UrlGenerator class and swap them using router.options.generator_class parameter. Then you could override the doGenerate method and replace %23 -> #.

Newmown answered 28/4, 2016 at 9:42 Comment(1)
The only part I am concerned with is the url generation. Not the url handling.Coss
I
2

In twig

<a href="{{ path('user_settings', { '_fragment': 'password' }) }}">
Illuminometer answered 4/4, 2019 at 12:58 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.