I need to be able to define routes where the /{_locale}
part is optional. This means I need these URLs to use the same controller:
my-domain.com/
(the locale will be set by a request listener)my-domain.com/[any-locale]/
Same goes with:
my-domain.com/my-page
(the locale will be set by a request listener)my-domain.com/[any-locale]/my-page
The problem is I can't define two class @Route
annotations as this isn't valid/accepted by Symfony; and I can't duplicate each and every route in my controller classes because there will be a large number and that would be really bad!
I've tried having only one class annotation but I couldn't get it to work. Here are my attempts:
First:
/**
* @Route("/{_locale}", requirements={"_locale": "(\w{2,3})?"})
*/
class DefaultController extends Controller {
/**
* @Route("/")
* @param Request $request
* @return Response
*/
public function indexAction(Request $request) {
return new Response('index '.$request->getLocale());
}
/**
* @Route("/my-page")
* @param Request $request
* @return Response
*/
public function testAction(Request $request) {
return new Response('test '.$request->getLocale());
}
}
Conclusions:
- Works
- Works
- Fails (because only
my-domain.com//my-page
would work) - Works
Second:
I thought the problem was the leading slash, so i tried this:
/**
* @Route("{slash_and_locale}", requirements={"slash_and_locale": "\/?(\w{2,3})?"}, defaults={"slash_and_locale": ""})
*/
class DefaultController extends Controller { // ...
Conclusions:
- Works
- Works
- Fails (same reason)
- Works
I've seen this (old) question but no proper answer has been submitted yet :(
Anyone with a suggestion? Would be really helpful, thanks!