Symfony2语言环境语言整页事件监听器

时间:2013-02-15 21:53:34

标签: symfony service kernel listener translation

我需要创建一个类似facebook lang系统的系统,当用户点击语言以示例france('fr')页面将重新加载并且将显示messages.fr.yml中的所有内容...

我尝试制作像/language/{localExtension}这样的路线,但当我在那里设置Locale然后重定向它就不起作用了......我不知道我假设它只是某个页面不是全局的?因为当我在控制器的顶部设置setLocale('fr')时,它可以工作......

我在使用www.example.com/contact/en/contact/fr

时发现了一些文章

但我希望/contact和以前选择的语言显示的内容。或者默认情况下'en'就像现在用户没有改变它...

我整天都在谷歌搜索,我认为应该用...来完成... service =>在kernel.request上监听器和...?或类似的东西。

以下是有趣的链接Symfony2 wrong locale detection?我认为这就是我所需要的?要么?我试图设置服务并创建监听器,但是出现了一些错误,我甚至不知道这是否是创建它的方式:/

2 个答案:

答案 0 :(得分:6)

是的,出于某种原因你需要使用一个监听器:

<?php

namespace Your\Bundle\Listener;

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;
  }

  if ($locale = $request->attributes->get('_locale')) {
      $request->getSession()->set('_locale', $locale);
  } else {
      $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
  }
  }

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

在service.xml中注册您的监听器:

<service id="my.listener" class="Your\Bundle\Listener\LocaleListener">
    <argument>%locale%</argument>
    <tag name="kernel.event_subscriber"/>
</service>

如何在twig模板中实现语言切换器的示例:

{% for locale in ['en', 'fr','zh'] %}
    <li>
      <a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale' : locale})) }}">
        {% if locale == 'en' %}
        <img title="English" src="{{ asset('bundles/fkmywebsite/images/UnitedStates.png') }}" alt="English" height="30" width="30"/>
        {% elseif locale == 'fr' %}
        <img title="Français" src="{{ asset('bundles/fkmywebsite/images/France.png') }}" alt="Français" height="30" width="30"/>
        {% endif %}
      </div>
    </li>
{% endfor %}

答案 1 :(得分:0)

听众的工作和帮助很多。我重用脚本在​​会话

中设置语言环境(带子标签区域)和语言(语言环境代码)
     <?php
    namespace Fer\CaveBundle\EventListener;
    use Symfony\Component\HttpKernel\Event\GetResponseEvent;
    use Symfony\Component\HttpKernel\KernelEvents;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Symfony\Component\HttpFoundation\Session\Session;
    use Symfony\Component\DependencyInjection\ContainerInterface;

    class LocaleListener implements EventSubscriberInterface
    {
        private $defaultLocale;
        private $locales;

    public function __construct($defaultLocale='es', ContainerInterface $container)
    {
        //values from configuration of my bundle
        $backend =  $container->getParameter('cave.backend');
        $this->locales = $backend['_locale'];  

    //    $this->locales = array( 'es'=>'es_ES'
    //                            'en'=>'en_GB,en_US',
    //                            'fr'=>'fr_FR,fr_BG'
    //                        );
        //default must exists in _locales array. locale_lookup Default: es_ES
        $this->defaultLocale = locale_lookup(array_keys($this->locales),
                                            $defaultLocale,
                                            false,
                                            current(explode(',',implode(',',array_values($this->locales)))));


    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        $session = $request->getSession();

        //  Locale Get parameters
        if($locale = $request->query->get('_locale'))
        {
            $this->setLocale($request, $session, $locale);
            return;
        }

        //  Locale Post parameters with custom form name
        if($locale = $request->request->get('_localeForm'))
        {
         $this->setLocale($request, $session, $locale['_locale']);
         return;
        }

        //  Locale session parameters
        if($locale = $session->get('_locale'))
        {
            $this->setLocale($request, $session, $locale);
            return;
        }    

        //Locale in browser
        if($locale = $request->getPreferredLanguage()){
            $this->setLocale($request, $session, $locale);
            return;
        }    

        $this->setLocale($request, $session, $this->defaultLocale);
        return;
    }

    public function setLocale($request,$session,$locale)
    {
            //search language and lookup, default first locale in language
            if(in_array(current(locale_parse($locale)),array_keys($this->locales))){
                $locale = locale_lookup(explode(',',$this->locales[current(locale_parse($locale))]),
                                    $locale,
                                    false,
                                    current(explode(',',$this->locales[current(locale_parse($locale))])));
            }else{
                $locale = $this->defaultLocale;
            }

            //set session parameter
            if($locale!==$session->get('_locale')){
                $session->set('_locale',$locale);
                $session->set('language', current(locale_parse($locale)));//language code
            }
            //Set the default PHP locale.(for translations)
            $request->setLocale($locale);
            //set post parameter
            $request->request->set('_locale',$locale);  
            //set get parameter
            $request->query->set('_locale',$locale);  


            return;
    }

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

    }
    ?>

如果发送帖子参数,控制器中的表单:

    public function indexAction()
    {
        $form = $this->get('form.factory')->createNamedBuilder('_localeForm')
             ->add('_locale', 'choice', array(
                'choices'   => array('en' => 'english', 'es' => 'Español'),//etc
                'required'  => true,
            ))->getForm();

            return $this->render(
            'myProject:myBundle:index.html.twig',
            array('_localeForm' => $form->createView())
        );
    }

示例树枝形式:

    <form  action="" method="post"  {{ form_enctype(_localeForm) }}>
    {{ form_widget(_localeForm)}} <br><br>
    <input type="submit" value="Enviar" />
    {{ form_rest(_localeForm) }}
    </form>

在url中发送语言环境,如果从具有twig函数的配置中获取语言环境数组,则更好:

    {% for locale in ('fer_cave.backend._locale'|caveParam)|keys %}
    <li {% if locale == app.session.get('language') %}class="active" style="color: red"{% endif %}>
    {#<a href="{{path(app.request.get('_route'), {'_locale': locale}) }}">{{ locale }}</a>#}
    {% set route = app.request.get('_route') %}
    {% set route_params = app.request.get('_route_params') %}
    <a href="{{ path(route, route_params | merge({ '_locale': locale })) }}">{{ locale }}</a>
    {% endfor %}
    {#
    Locale in session: {{app.session.get('_locale')}}<br>
    Language in session: {{app.session.get('language')}}<br>
    Locale as get param: {{app.request.get('_locale')}}<br>
    Locale as post {{app.request.request.get('_locale')}}
    #}

如果要从捆绑配置中检索区域设置,请将serviceContainer添加到侦听器:

    <service id="cave.listener" class="Fer\CaveBundle\EventListener\LocaleListener">
        <argument>%locale%</argument>
        <argument type="service" id="service_container" />
        <tag name="kernel.event_subscriber"/>
    </service>

为什么不,myProject / myBUndle / DependencyInjection中的示例配置数组

            //-------------------ejemplo de backend-------------------//  
     ->arrayNode('backend')
        ->addDefaultsIfNotSet()
        ->children()
            ->arrayNode('_locale')
                ->addDefaultsIfNotSet()
                ->children()
                    ->scalarNode('es')->defaultValue('es_ES')->end()//language=>region
                    ->scalarNode('en')->defaultValue('en_GB,en_US')->end()//
                    ->scalarNode('fr')->defaultValue('fr_FR,fr_BG')->end()//                
                ->end()
            ->end()//end arrayNode('_locale')
            ->scalarNode('encoding')->defaultValue('UTF-8')->end()
        ->end()
    ->end()//end arrayNode('backend')            

捆绑包的配置参数中的清洁程序:

fer_cave.backend: 
  _locale: {es: [es_ES],en: [en_GB,en_US],fr: [fr_FR,fr_BG]}
  encoding: UTF-8
cave.frontend: 
  _locale: {es: es_ES}    
  encoding: UTF-8 

现在我可以使用get,post或browser配置设置Session _locale和语言。

希望用我的英语清楚并且抱歉因为不断编辑文本。