Robert W. Hunter February 2016

Symfony2 character between parameters in route

So I have this route

path: /view/{category}-{subcategory}

And I'm trying to render this route in my twig

href="{{ path('my_route', {category: cat.slug, subcategory: sub.slug }) }}"

But symfony is throwing me this error

An exception has been thrown during the rendering of a template ("Parameter "category" for route "my_route" must match "[^/-]++" ("food-cheap" given)

Isn't it supossed to auto generate the - character as I'm setting the real parameters? If I change - to / it works, but i don't want to use a slash because it's not a URI inside category.

It does also work if I use this

requirements: category: ".*"

But using slugs (as it's the point of this) for the parameters, goes crazy.

For example category: something subcategory: super-size

URI would be /view/something-super-size but Symfony2 says that

category = something-super

and

subcategory = size

Because everything has - and it doesn't know where to stop in the regex pattern.

I've found a strange behaviour...

If I manually type the URL

http://localhost/view/something-super-size

It goes correctly to it's controller, without problems and without using requirements so maybe the problem is at the {{ path() }} method...

Answers


chalasr February 2016

To make your route working with a dash as segments separator, declare your route like this :

my_route:
    path: /view/{category}-{subcategory}
    defaults:
        _controller: YourBundle:Controller:method
    requirements:
        category: "[a-zA-Z1-9\-_\/]+"

Now the dash will be automatically added between your params when use
href="{{ path('my_route', {category: cat.slug, subcategory: sub.slug }) }}"

EDIT

To be more precise, with the given regexp, the dash will be considered as uri segment separator, and will not be part of a parameter.
Parameters are intact (doesn't contain the -) and when you generate the url with the path method, the - will be automatically added between the parameters. The regexp just make it working.

See it in action

Post Status

Asked in February 2016
Viewed 2,918 times
Voted 9
Answered 1 times

Search




Leave an answer