Symfony2 how to allow slug with dashes in routes regex?

自作多情 提交于 2019-12-18 03:56:25

问题


My route (slug contains dashes!):

region:
  pattern: /regione/{slug}-{id}
  defaults: { _controller: SWAItaliaInCifreBundle:Default:region }

In Twig template:

{% for r in regions %}
    <a href='{{ path('region', { 'slug':r.slug, 'id':r.id }) }}'>{{ r.name }}</a>
{% endfor %}

I'm getting an error about regular expression matching. Question: why Symfony2 does not permit dashes in url? How can i specify that my route contains dashes (and it's perfectly fine)?

An exception has been thrown during the rendering of a template ("Parameter "slug" for route "region" must match "[^/-]+?" ("valle-d-aosta-vallee-d-aoste" given).")


回答1:


Slashes are by default forbidden. You can enable them by changing the default requirements. In your case it'd be also good to give requirements for the id as it's separated with dash.

See example below.

region:
    pattern: /regione/{slug}-{id}
    defaults:
        _controller: SWAItaliaInCifreBundle:Default:region
    requirements:
        slug: "[a-zA-Z1-9\-_\/]+"
        id: "\d+"



回答2:


This regex works for me. ({id} requirement suggested by Michael)

region:
  pattern: /regione/{slug}-{id}
  defaults: { _controller: SWAItaliaInCifreBundle:Default:region }
  requirements:
    slug: "[a-zA-Z0-9-_/]+"
    id: "\d+"



回答3:


if you try this it will throw a error like this:

An exception has been thrown during the rendering of a template ("Parameter "slug" for route "routing_whatever" must match "[a-zA-Z0-9-_/]+" ("Topics/Virtualization Security" given).") in ...

as viewed in http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html you must use:

slug: ".+"



来源:https://stackoverflow.com/questions/7706887/symfony2-how-to-allow-slug-with-dashes-in-routes-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!