0

Symfony 5.1

I'm updating some legacy code and I need the following routes to match:
/article/ <--- matches default page 1 and has trailing slash
/article/2 <--- matches pages 2 through n with no trailing slash

If I use the route annotation...

* @Route("/article/{page}", name="article_show", requirements={"page"="\d+"})
* @param int $page
* @return Response
*/
public function show(int $page = 1) {

it redirects /article/ to /article removing the trailing slash. /article/2 works.

How do I keep the trailing slash when the page is 1?

hipnosis
  • 618
  • 1
  • 8
  • 13

1 Answers1

1

According to https://symfony.com/doc/4.1/routing/optional_placeholders.html "Routes with optional parameters at the end will not match on requests with a trailing slash (i.e. /blog/ will not match, /blog will match)."

So if you don't absolutely care about having a trailing slash, just add a defaults={"page"=1} . However if you really do... I don't see a better option than adding a second @Route with "/article/". Since your method has a default value for the parameter, it should work.

FTW
  • 922
  • 1
  • 7
  • 19
  • I had considered the second route, but thought it would mean lots of messy edits in many templates. Your answer helped me realize I could have two routes, but only need to reference the one with page numbers in the templates. Thanks! – hipnosis Sep 11 '20 at 18:55