3
votes

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

1
Of couse not! Generating route path Is up to you. Symfony will not generate any - char. Your regex should be: ^\/view\/(\w+\-\w+) or just /view/{slug} and in twig: path('my_route', {category: cat.slug ~ "-" ~ sub.slug })felipsmartins
Using my answer, the dash is auto-generated using the path method.chalasr

1 Answers

1
votes

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