Seriescw Esxille
Seriescw Esxille

Reputation: 301

how to get the current locale in symfony 2.3?

How can I get the curent locale in Symfony 2.3 ?

I have a url like this: /{_locale}/blog/article with FR as a default parameter. I try the following: $this->get('request')->getLocale()

but it always give me the default parameter.And i am aware that i can use $this->get('session')->set('_locale', 'fr');

but the problem is that when the user first visit my website he has nothing stored in his session.

Upvotes: 24

Views: 37947

Answers (4)

jave.web
jave.web

Reputation: 15032

For PHP 8.1+ with Symfony 6+ similarly to Hasitha's answer:

Use DI(Dependency Injection) to get the RequestStack instance

public function __construct(
    private readonly RequestStack $requestStack,
) {}

Then you can do something like this:

$this->requestStack->getCurrentRequest()?->getLocale();

or even this if you want to ensure at least some locale is returned as string:

$this->requestStack->getCurrentRequest()?->getLocale() ?? \Locale::getDefault();

Related symfony docs: https://symfony.com/doc/current/translation.html#handling-the-user-s-locale

PS: I am not sure why the current request can be nullable, my guess is maybe when ran in the command or some very early messaround.

Upvotes: 1

Hasitha Diluka
Hasitha Diluka

Reputation: 766

  • If you want to access locale inside a service or controller you can use @request_stack to inject RequestStack.
  • RequestStack has getCurrentRequest() method to get current request. Then you can use getLocale() to get user current locale.

Upvotes: 2

AlexioVay
AlexioVay

Reputation: 4527

Simply use $request->getLocale(); in Symfony 4 since this seems to the top link when you search in Google for this topic.

Upvotes: 3

Azam Alvi
Azam Alvi

Reputation: 7055

You can get current locale by this

 $request = $this->get('request');
 echo $request->getLocale();

Upvotes: 47

Related Questions