symfonytwig

urlencode in twig path function


I have this route:

_view_tag:
    pattern:  /topic/{tid}
    defaults: {_controller: "MyCoreBundle:ViewTag:index" }

And I want to show url like this: example.com/topic/Web+development. I use href="topic/{{ topicname|url_encode() }}". It is works, but of course it is not proper way, so I change to href="{{ path('_view_tag', {'tid': topicname|url_encode() } ) }}". But it is not showing example.com/topic/Web+development, it shows example.com/topic/Web%2Bdevelopment.

I also try this:

{% set _tid = topicname|url_encode() %}
<a href="{{ path('_view_tag', {'tid': _tid } ) }}" ...

But still not working

How to make it show example.com/topic/Web+development using twig path function?


Solution

  • The path function takes care of url-encoding for you. Your problem is that your space got encoded twice: first to a +, then that got converted to %2b. This will work:

    path('_view_tag', { 'tid': topicname } )