2

Have some trouble getting all available locales in Symfony 3. The idea is to create a custom language switcher.

I have

parameters:
locale: en
app.locales: en|fr|ru

I can get requested locale or user stored in session locale. But how can i get all parameters.app.locales in Service of Controller on finally in Twig? So that i can have ar array like en|fr|ru and so on.

Thanks.

2 Answers2

0

Because you have the locales specified as a parameter you can retrieve the parameter value depending on where you want it:

1. As service argument:

Pass the locales via constructor parameters by specifying in the service definition:

Service:

class SomeService {

    private $locales;

    public function __construct(array $locales)
    {
        $this->locales = $locales;
    }

    ...
}

Service definition:

...\Service\SomeService:
    arguments:
        - '%app.locales%'

2. With the service container:

You can also retrieve parameters via the service container:

$locales = $this->container->getParameter('app.locales');

3. Pass locales to Twig

After getting the locales via above ways you can just pass them as variable just like normal Twig variables when rendering a template:

return $this->render('some.template.html.twig', [
    'locales' => $locales,
]);

4. Set specific Twig parameters:

How to get config parameters in Symfony2 Twig Templates

goulashsoup
  • 2,639
  • 2
  • 34
  • 60
0

Just came across this in Symfony 5. Seems that there is no method for it in TranslatorInterface

Therefore the simplest way in my case would be to get all values from parameters

$locales = $this->getParameter('app_locales');

In my case

app_locales: en|fr|de|es|cs|nl|ru|uk|ro|pt_BR|pl|it|ja|id|ca|sl|hr|zh_CN|bg|tr|lt

defined in services.yaml

Marcin
  • 195
  • 1
  • 7