在 Symfony 2.1 中设置语言环境 [英] Set locale in Symfony 2.1

查看:27
本文介绍了在 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:        "FKMyWebsiteBundleListenerLocaleListener"

我的路由:

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 的声明:vendorsymfonysymfonysrcSymfonyBundleFrameworkBundle资源配置web.xml)

The declaration of the LocaleListener in yml (inspired by the current declaration of the new LocaleListener: vendorsymfonysymfonysrcSymfonyBundleFrameworkBundleResourcesconfigweb.xml)

services:
    my_listener:
        class: "FKMyWebsiteBundleListenerLocaleListener"
        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 SymfonyComponentHttpFoundationRedirectResponse($LocalizedUrl);

这篇关于在 Symfony 2.1 中设置语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆