Created
July 2, 2013 07:36
-
-
Save Swop/5907406 to your computer and use it in GitHub Desktop.
Create a culture switch in Symfony2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)), | |
); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<service id="my.listener" class="Your\Bundle\Listener\LocaleListener"> | |
<argument>%locale%</argument> | |
<tag name="kernel.event_subscriber"/> | |
</service> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% 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 %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment