Search code examples
symfonysymfony-routing

Symfony default locale without specifying in URL


I would like to configure the Symfony locale options so that I can successfully access the following routes:

/route
/{locale}/route

Currently, I can access /{locale}/route and I get my view, however, /route returns a No route found for "GET /route". My configuration is as follows:

#app/config/parameters.yml
parameters:
    locale: en

#app/config/config.yml
parameters:
    app_locales: en|fr
framework:
    translator: { fallback: "%locale%" }
    default_locale: "%locale%"

#app/config/routing.yml
app:
    resource: '@AppBundle/Controller/'
    type: annotation

My Controller has the following annotations:

#src/AppBundle/Controller/Admin/MyController.php
/**
 *
 * @Route(
 *     "/{_locale}/admin/my",
 *     defaults={"_locale":"%locale%"},
 *     requirements={"_locale":"%app_locales%"}
 *     )
 */
class MyController extends Controller
{
    /**
     * @Route("/", name="admin_my_list")
     * @Method("GET")
     */
    public function listAction()
    {
        ...
    }
}

If I specifically include the locale, it all works. If I exclude the locale, I get the No route found error.


Solution

  • You have to define another route to cover the scenario without the provided locale, try changing your route definition to:

    #src/AppBundle/Controller/Admin/MyController.php
    
    class MyController extends Controller
    {
        /**
         * @Route(
         *     "/admin/my",
         *     defaults={"_locale":"%locale%"},
         *     )
         * @Route(
         *     "/{_locale}/admin/my",
         *     requirements={"_locale":"%app_locales%"}
         *     )
         * @Method("GET")
         */
        public function listAction()
        {
            ...
        }
    }