0
votes

I can not understand the page translation mechanism. Translations for a specific language I keep in the yml file Translation can be obtained in two ways:

  1. Holding the currently selected translation in the session

How can I change my language? The documentation even gives you a ready code https://symfony.com/doc/current/session/locale_sticky_session.html

Only at what point does the language change? I create a separate controller to which I pass a parameter using GET and execute the code in the controller?

$lang = $request->query->get('lang', null);
if(!is_null($lang)) { 
    request->setLocale($lang);
}
return $this->redirect($this->generateUrl('index.index'));

In order to not write the same code in any controller, I should have one controller that only changes the language and returns the page to the previous one. Only returning to the previous page via redirect does not pass the Request with a new language only the class given in the documentation uses the default language.

  1. Each time providing a translation for the page in the link

The first problem that I encounter is having the default routing for the @Route ("/") home page will not pass me localhost:8000/en/ because Symfony will look for the en controller, which is the choice of language, not the controller. The solution is to provide the path localhost:8000/index/en But at this moment I'm blocking the possibility of displaying the page by giving only the address of the page. The @Route option ("/{_ locale}", defaults = {"_locale" = "en"}) does not work and I do not understand why, because I always have to specify pl / en etc. to display the language.

When reading the documentation, I should do the following:

  1. Configuration in the file config / packages / translation.yaml

default_locale: 'en' <- specifies the default language translator: ~ fallbacks: ['en'] <- defines which language will be loaded if you provide an incorrect language via _locale

  1. File: config / services.yaml parameters: locale: 'en'
  2. The config / translation.yaml file

    framework: default_locale: 'en' translator: ~

1
What version of Symfony is your application based on?EmilCataranciuc
Symfony 4.0.6 - PHP 7.2.2Kevin

1 Answers

-2
votes

To make localization work for your users you have to follow three tutorials: https://symfony.com/doc/current/translation.html https://symfony.com/doc/current/translation/locale.html and https://symfony.com/doc/current/session/locale_sticky_session.html The first one explains how to setup translations and how to use them. The second explains how to read the locale of the current session and that you should use _locale parameter to set your routes (as a prefix would be the best option in the beginning). The third tutorial explains how to make the locale sticky to user session (so that the user doesn't have to type the correct URL in the browser each time). All these work together, not as separate options.