如何获取 Symfony 2.3 中的当前语言环境?
我有一个这样的网址:
/{_locale}/blog/article
以 FR 作为默认参数。
我尝试以下操作:
$this->get('request')->getLocale()
但它总是给我默认参数。而且我知道我可以使用
$this->get('session')->set('_locale', 'fr');
但问题是,当用户第一次访问我的网站时,他的会话中没有存储任何内容。
您可以通过此获取当前区域设置
$request = $this->get('request');
echo $request->getLocale();
只需在 Symfony 4 中使用
$request->getLocale();
,因为当您在 Google 中搜索此主题时,这似乎是顶部链接。
@request_stack
来注入 RequestStack
。RequestStack
有 getCurrentRequest()
方法来获取当前请求。然后您可以使用 getLocale()
获取用户当前区域设置。对于 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:我不确定为什么当前请求可以为空,我的猜测可能是在命令中运行时或一些非常早期的混乱。