gpt4 book ai didi

symfony - 请求中的 Symfony 2.3 语言环境翻译

转载 作者:行者123 更新时间:2023-12-01 11:41:50 24 4
gpt4 key购买 nike

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

我创建了这个 Controller :

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

刷新页面时不显示变化。为什么?

最佳答案

基于 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)),
);
}
}

服务.yml

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

最后,你可以在你的 Controller 中使用:

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

在此link你有一个非常相似的问题。

关于symfony - 请求中的 Symfony 2.3 语言环境翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19484027/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com