Yes for some reason you need to use a listener:
<?php
namespace 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:
{% 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 %}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…