如何在 symfony 2.3 中获取当前语言环境?

问题描述 投票:0回答:4

如何获取 Symfony 2.3 中的当前语言环境?

我有一个这样的网址:

/{_locale}/blog/article
以 FR 作为默认参数。 我尝试以下操作:
$this->get('request')->getLocale()

但它总是给我默认参数。而且我知道我可以使用

$this->get('session')->set('_locale', 'fr');

但问题是,当用户第一次访问我的网站时,他的会话中没有存储任何内容。

php symfony
4个回答
46
投票

您可以通过此获取当前区域设置

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

3
投票

只需在 Symfony 4 中使用

$request->getLocale();
,因为当您在 Google 中搜索此主题时,这似乎是顶部链接。


2
投票
  • 如果您想访问服务或控制器内的区域设置,您可以使用
    @request_stack
    来注入
    RequestStack
  • RequestStack
    getCurrentRequest()
    方法来获取当前请求。然后您可以使用
    getLocale()
    获取用户当前区域设置。

0
投票

对于 PHP 8.1+ 和 Symfony 6+ 与 Hasitha 的答案类似:

使用DI(依赖注入)获取

RequestStack
实例

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

然后你可以这样做:

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

或者甚至是这样,如果你想确保至少 some 语言环境作为字符串返回:

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

相关 symfony 文档:https://symfony.com/doc/current/translation.html#handling-the-user-s-locale

PS:我不确定为什么当前请求可以为空,我的猜测可能是在命令中运行时或一些非常早期的混乱。

© www.soinside.com 2019 - 2024. All rights reserved.