Symfony 4 with translations, no route to / without _locale

1k views Asked by At

I created a Symfony 4.4.8 project with translations to English and French languages, so I followed the steps:
https://symfony.com/doc/current/translation.html

and set:

config/packages/translation.yaml

framework:
    default_locale: 'fr'
    translator:
        default_path: '%kernel.project_dir%/translations'
        fallbacks: ['en', 'fr']

config/routes/annotations.yaml

controllers:
    resource: ../../src/Controller/
    type: annotation
    prefix: /{_locale}/
    requirements:
        _locale: fr|en

and a src/Controller/HomeController.php with

class HomeController extends AbstractController
{
    private $session;
    
    public function __construct(SessionInterface $session)
    {
        $this->session = $session;
    }

    /**
     * @Route("/", name="home")
     */
    public function index() {
        return $this->render('home/index.html.twig', [
            'controller_name' => 'HomeController',
        ]);
        
    }

I have the translation files in translations folder and when I run localhost:8000/fr or localhost:8000/en, it works fine, my home/index.html.twig is shown.

The issue is when I run localhost:8000/, it shows me the default Welcome to Symfony page with "You're seeing this page because you haven't configured any homepage URL."

Is this solution for sf2 will work on sf4?
Is anybody know how to solve it ?

I tested also to change the route in HomeController to:
@Route("/{_locale}", name="home", defaults={"_locale"="fr"}
but it returns exception:
Route pattern "/{_locale}/{_locale}" cannot reference variable name "_locale" more than once.

2

There are 2 answers

0
bcag2 On BEST ANSWER

workaround, added:
RedirectMatch ^/$ /fr
in my virtualhost (with apache2 server)

pure symfony solution shoud be better !

2
Nover On

I would guess a bad routing configuration. I couldn't recall a default behaviour where we can set the locale by adding the locale code in the URL so I would guess it is something your added ;)

Symfony resolves the route in the same order as you declare the route. So one solution would be to import 2 times the same route but with the prefix:

# config/route.yaml
app_front:
    type: annotation
    resource: '../src/Controller/*.php'
    prefix: /
    options:
        expose: true

app_localized_front:
    type: annotation
    resource: '../src/Controller/*.php'
    name_prefix: localized_
    prefix: /{locale}
    options:
        expose: true

I know the previous config works, but I don't know if this is the more elegant way to do it :)