用户选择语言并保存所有会话的语言环境

时间:2017-10-04 10:15:25

标签: php symfony session multilingual

我正在使用多种语言的页面工作。 我在树枝主页上有一个按钮可以在语言之间切换。 当用户单击按钮选择语言时,我正在尝试设置这样的语言环境:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Slideshow Test</title>
    <link rel="stylesheet" href="./style.css">
    <link rel="shortcut icon" href="./img/Shortcut.ico" type="image/ico">

  </head>
  <body class="a12">
  <?php /**$id = $_GET['id']; **/?>
    <div align="center">
                  <tr height="460">
                    <td class="a10" height="460" width="566">
                      <div align="center"></div>
                      <img src="<? echo htmlspecialchars($_GET['id']); ?>.jpg" alt="an image" height="460" border="0">
                    </td>
                  </tr>
    </div>
  </body>
</html>

但是当我在同一个会话中转到另一个页面时,该语言又回到默认状态。

如何在所有用户会话中保存public function indexLangAction(Request $request, $lang) { $session = $this->get('session'); if ($session->has("_locale") && $lang !== $session->get("_locale")) { $session->set("_locale", $lang); return new RedirectResponse('/' . $lang); } return $this->render('default/index.html.twig', [ 'base_dir' => realpath($this- >getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR, ]); }

设置_locale的最佳方法是什么?我怎样才能从树枝上打电话给控制器?当用户单击按钮更改语言时,如何调用控制器?

_locale

这是调用路线privacy_lang: path: /{_locale}/privacy defaults: { _controller: AppBundle:Documents:privacy } requirements: _locale: en|es|ca 的树枝中的链接:

privacy_lang

1 个答案:

答案 0 :(得分:0)

使用监听器。首先创建服务:

AppBundle\EventListener\LocaleListener:
    tags:
        - { name: kernel.event_subscriber }

LocaleListener.php:

namespace AppBundle\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 ($locale = $request->attributes->get('_locale')) {
        $request->getSession()->set('_locale', $locale);
    } else {
        $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
    }
}

public static function getSubscribedEvents()
{
    return [KernelEvents::REQUEST => array(array('onKernelRequest', 15))];
}

}

更改语言控制器:

$request->getSession()->set('_locale', 'fr');