在Symfony 2.1中设置区域设置 [英] Set locale in Symfony 2.1
问题描述
我正在尝试在我的symfony 2.1网站上使用语言切换器.
I am trying to have a language switcher on my symfony 2.1 website.
我遵循了官方文档,设置了翻译文件,但设置了$ request-> setLocale('en_US');的语言环境似乎不起作用.经过一番研究,我发现了这个问题,它提供了一个答案的开始此侦听器技术.
I followed the official documentation, set the translation files but setting the locale with $request->setLocale('en_US'); doesn't seem to work. After some research, I found this question which provides a beginning of an answer with this listener technique.
但是,我仍然无法使其正常运行,我不太确定我的监听器声明,这有问题吗?
However, I still don't manage to have it working, I'm not so sure about my listener declaration, is something wrong with it?
我的控制器:
public function englishAction(Request $request)
{
$this->get('session')->set('_locale', 'en_US');
return $this->redirect($request->headers->get('referer'));
}
config.yml中的服务声明:
Service declaration in config.yml:
services:
my_listener:
class: "FK\MyWebsiteBundle\Listener\LocaleListener"
我的路线:
homepage:
pattern: /{_locale}
defaults: { _controller: FKMyWebsiteBundle:Default:index, _locale: en }
requirements:
_locale: en|fr|cn
about:
pattern: /{_locale}/about
defaults: { _controller: FKMyWebsiteBundle:Default:about, _locale: en }
requirements:
_locale: en|fr|cn
推荐答案
以yml表示LocaleListener的声明(受新LocaleListener的当前声明的启发:\ vendor \ symfony \ symfony \ src \ Symfony \ Bundle \ FrameworkBundle \ Resources \ config \ web.xml)
The declaration of the LocaleListener in yml (inspired by the current declaration of the new LocaleListener: \vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Resources\config\web.xml)
services:
my_listener:
class: "FK\MyWebsiteBundle\Listener\LocaleListener"
arguments: [%locale%]
tags:
- { name: kernel.event_subscriber }
一些摘要:
模板中的语言切换器:
{% for locale in ['en', 'fr', 'cn'] %}
<li {% if locale == app.request.locale %}class="active"{% endif %}>
<a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale' : locale})) }}">{{ locale }}</a>
</li>
{% endfor %}
从控制器更改语言环境的重定向:
A redirection with locale change from a controller:
$LocalizedUrl = $this->get('router')->generate(
$request->attributes->get('_route'),
['_locale' => $locale] + $request->attributes->get('_route_params')
);
return new \Symfony\Component\HttpFoundation\RedirectResponse($LocalizedUrl);
这篇关于在Symfony 2.1中设置区域设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!