要求翻译 Symfony 2.3 语言环境 [英] Translations in Symfony 2.3 locale in request

查看:31
本文介绍了要求翻译 Symfony 2.3 语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Symfony 2.3 中更改语言环境?

How can I change locale in Symfony 2.3 ?

我创建了这个控制器:

public function changelocaleAction($lang)
{
    $request = $this->get('request');
    $request->setLocale($lang);
    return $this->redirect($request->headers->get('referer'));
}

刷新页面时不显示更改.为什么?

It doesn't show changes when the page is refreshed. Why?

推荐答案

基于 Symfony2 文档:

Based on Symfony2 documentation:

namespace Acme\LocaleBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class LocaleListener implements EventSubscriberInterface
{
    private $defaultLocale;

    public function __construct($defaultLocale = 'en')
    {
        $this->defaultLocale = $defaultLocale;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if (!$request->hasPreviousSession()) {
            return;
        }

        // try to see if the locale has been set as a _locale routing parameter
        if ($locale = $request->attributes->get('_locale')) {
            $request->getSession()->set('_locale', $locale);
        } else {
            // if no explicit locale has been set on this request, use one from the session
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            // must be registered before the default Locale listener
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
        );
    }
}

services.yml

services.yml

services:
    acme_locale.locale_listener:
        class: Acme\LocaleBundle\EventListener\LocaleListener
        arguments: ["%kernel.default_locale%"]
        tags:
            - { name: kernel.event_subscriber }

最后,您可以在控制器中使用:

Finally, you can use in your controller:

$locale = $this->getRequest()->getLocale();

在这个链接中,您有一个非常相似的问题.

In this link you have a very similar question.

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

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