更改语言环境symfony 2.3 [英] change locale symfony 2.3
问题描述
我刚开始用symfony 我正在尝试建立一个多语言网站,但是在更改语言环境时遇到了问题
I just began with symfony I'm trying to build a multilang website but I have a problem to change the locale
我阅读了一些帖子,并阅读了有关此内容的文档,但是语言环境没有改变,我尝试:
I read some posts and I read the documentation about this but the locale don't change, I try:
public function indexAction()
{
$this->get('session')->set('_locale', 'fr');
$request = $this->getRequest();
$locale = $request->getLocale();
return $this->render('PhoneMainBundle:Default:index.html.twig',array('locale'=>$locale));
}
但是$ locale中的值始终为'en'(我的默认语言环境)
but the value in $locale is always 'en' (my default locale)
我也尝试
public function indexAction()
{
$this->get('session')->set('_locale', 'fr');
$request = $this->getRequest();
$request->setLocale('fr');
$locale = $request->getLocale();
return $this->render('PhoneMainBundle:Default:index.html.twig',array('locale'=>$locale));
}
在这种情况下,$ locale是fr,但是翻译总是来自messages.en.yml
In this case $locale is fr but the translations are always from messages.en.yml
我想第一次使用$ _SERVER ['HTTP_ACCEPT_LANGUAGE']检测用户语言环境,也许在每个页面实现时都使用列表器?
I'd like in a first time to detect the user locale using $_SERVER['HTTP_ACCEPT_LANGUAGE'], maybe using a listner on each page actualisation ?
,然后我将创建一条更改区域设置的路线
and after I will create a route to change the locale
但是我想找到一种更改语言环境的方法.
But I 'd like to find a way to change the locale.
感谢您的帮助
推荐答案
基于这个答案.
LanguageListener.php:
<?php
namespace Acme\UserBundle\EventListener;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class LanguageListener
{
private $session;
public function setSession(Session $session)
{
$this->session = $session;
}
public function setLocale(GetResponseEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
$request = $event->getRequest();
$request->setLocale($request->getPreferredLanguage(array('en', 'de')));
}
}
services.yml:
acme.language.kernel_request_listener:
class: Acme\UserBundle\EventListener\LanguageListener
tags:
- { name: kernel.event_listener, event: kernel.request, method: setLocale }
关于树枝中错误的语言环境检测,可能有很多不同的原因.通过SO搜索,您肯定会找到答案.确保正确定义了"_local"变量,确保将语言文件放置在正确的位置,等等.最后,再次阅读文档的最新版本:
About wrong locale detection in twig, there could be a lot of different causes. Search through the SO, you'll definitely find the answer. Make sure that your '_local' var is defined right, make sure that you put your languages files in the right place, etc. FInally, read again the last version of the documentation: http://symfony.com/doc/current/book/translation.html
这篇关于更改语言环境symfony 2.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!