检测语言环境并更改URL(重定向)以包括语言环境 [英] Detect locale and alter url (redirect) to include locale

查看:102
本文介绍了检测语言环境并更改URL(重定向)以包括语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是检测用户浏览器的语言并将其重定向到包含url中的语言环境的页面.

What i want to do is, to detect the language of a users browser and redirect him to a page containing the locale in url.

我认为,最简单的方法是注册内核侦听器.这就是我所做的:

I thought, the easiest way would be, to register a kernel listener. So that is what i did:

services:
    kernel__request_listener:
        class: Me\MainBundle\Listener\KernelRequestListener
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
        calls:
            - [ setContainer, [ @service_container ] ]

KernelRequestListener.php

KernelRequestListener.php

...
/**
 * @Service
 */
class KernelRequestListener
{
    /**
     * @Observe("kernel.request")
     */
    public function onKernelRequest( GetResponseEvent $response )
    {

    if( $newLocale = $this->newLocale() )
    {
        $parmArray = $request->get('_route_params');
        $parmArray['_locale'] = $newLocale;

        $redirectResponse = new RedirectResponse( $this->getContainer()->get('router')->generate($request->get('_route'), $parmArray) );
        $redirectResponse->headers->setCookie( new Cookie('b_locale', $newLocale, time() + 2592000) );

        $response->setResponse( $redirectResponse );
    }
    }
...
}

$ this-> newLocale()方法仅检测用户是否应重定向到另一种语言,并返回新的语言代码(即DE或FR).

The method $this->newLocale() just detects if the user should be redirected to another language and returns the new language code (i.e. DE or FR).

问题来了: 我正在使用Assetics压缩js文件,并使用jms/i18n-routing-bundle进行基于语言环境的路由.当内核侦听器切换语言环境时,页面开始一遍又一遍地加载js文件.另外,在多个页面(例如,探查器,登录/注销等)中,不应进行任何重定向,因为这没有意义,也不会破坏任何东西.

Here comes the problem: I am using assetics to compress the js files and jms/i18n-routing-bundle to do the locale-based routing. When the kernel listener switches locale, the page starts loading the js files over and over again. also, there are several pages (i.e. the profiler, login/logout etc.) where no redirect should take place as it makes no sense or breaks smthing.

是内核侦听器进行此类重定向的正确位置,还是有更好的位置?如何解决以上问题?

Is a kernel listener the right place to do such a redirection or is there any better place. How to resolve the problems above?

推荐答案

在您的代码之前添加:

public function onKernelRequest(GetResponseEvent $event)
{
    if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
        return;
    }

    $request = $event->getRequest();
    if ($request->getRequestFormat() !== 'html') {
        return;
    }

    [CODE]

这篇关于检测语言环境并更改URL(重定向)以包括语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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