Symfony2 locale languages whole page event listener

前端 未结 2 1043
时光取名叫无心
时光取名叫无心 2020-12-10 20:29

I need to create a system like the facebook lang system when a user clicks on language to example france(\'fr\') the page will reload and all the content in messages.fr.yml

2条回答
  •  萌比男神i
    2020-12-10 20:49

    Yes for some reason you need to use a listener:

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

    Register your listener in your service.xml:

    
        %locale%
        
    
    

    An example how to implement the language switcher in your twig template:

    {% for locale in ['en', 'fr','zh'] %}
        
  • {% if locale == 'en' %} English {% elseif locale == 'fr' %} Français {% endif %}
  • {% endfor %}

提交回复
热议问题