我试图制作类似 /language/{localExtension} 的路线,但是当我在那里 setLocale 然后重定向它没有用...我不知道我假设它只是针对某个页面不是全球性的?因为当我在控制器顶部设置 setLocale('fr') 时,它会起作用......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 will be displayed...我在使用 www.example.com/contact/en、/contact/fr 等时发现了一些文章I tried to make route like /language/{localExtension} but when I setLocale there and then redirected it didn't work... I don't know i assuming its just for certain page not global? Because when i set setLocale('fr') at the top of my controller it works...但我想要 /contact 和以前选择的语言显示的内容.或者当用户没有改变它时默认'en'就像现在......I found some articles when is using the www.example.com/contact/en, /contact/fr etc我整天都在谷歌上搜索,我认为应该用...服务=>监听器和...在kernel.request上完成?或类似的东西.But i want /contact and content displayed from previous chosen language. Or default 'en' like now when user didn't change it...这里有一个有趣的链接 Symfony2 错误的语言环境检测? 我认为这就是我需要的?或者?我尝试设置服务并创建侦听器,但出现了一些错误,我什至不知道这是否是创建它的方式:/I was googling all day and i think it should be done with... service => listener and... on kernel.request? or something like that.推荐答案是的,出于某种原因您需要使用侦听器: 解决方案Yes for some reason you need to use a listener:在你的 service.xml 中注册你的监听器:<?phpnamespace YourBundleListener;use SymfonyComponentHttpKernelEventGetResponseEvent;use SymfonyComponentHttpKernelKernelEvents;use SymfonyComponentEventDispatcherEventSubscriberInterface;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)), ); }}?>Register your listener in your service.xml:如何在树枝模板中实现语言切换器的示例:<service id="my.listener" class="YourBundleListenerLocaleListener"> <argument>%locale%</argument> <tag name="kernel.event_subscriber"/></service>An example how to implement the language switcher in your twig template:{% 结束为 %} 这篇关于Symfony2 locale 语言整页事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-02 02:54
查看更多