Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 how to allow slug with dashes in routes regex?

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).")

like image 863
gremo Avatar asked Oct 09 '11 22:10

gremo


1 Answers

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+"
like image 130
Jakub Zalas Avatar answered Sep 23 '22 13:09

Jakub Zalas