I'd like to implement locale switcher, but it seems with no luck...
The code below doesn't work because the (Referrer) contains the old value of locale...
How can I redirect to the old Referrer URI with a new value of locale?
-- routing.yml
hello:
pattern: /{_locale}/hello/{name}
defaults: { _controller: JetInformBundle:Default:index, name: 'alexander' }
requirements:
_locale: ^en|de|ru|uk$
about:
pattern: /{_locale}/about
defaults: { _controller: JetInformBundle:Default:about }
requirements:
_locale: ^en|de|ru|uk$
locale:
pattern: /locale/{locale}
defaults: { _controller: JetInformBundle:Locale:index }
-- DefaultController.php
<?php
namespace Jet\InformBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
{
public function indexAction($name, Request $request)
{
$request->getSession()->set('referrer', $request->getRequestUri());
return $this->render('JetInformBundle:Default:index.html.twig',
array('name' => $name));
}
public function aboutAction(Request $request)
{
$request->getSession()->set('referrer', $request->getRequestUri());
return $this->render('JetInformBundle:Default:about.html.twig'));
}
}
-- LocaleController.php
<?php
namespace Jet\InformBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
class LocaleController extends Controller
{
public function indexAction($locale, Request $request)
{
$session = $request->getSession();
if ($request->hasSession())
$session->setLocale($locale);
return $this->redirect($session->get('referrer'));
}
}
-- index.html.twig
{% extends '::base.html.twig' %}
{% block body %}
<h1>{% trans %}hello.name{% endtrans %} {{ name }}!</h1>
<h3>{% trans %}your.locale{% endtrans %} [{{ app.request.get('_locale') }}]</h3>
{% include 'JetInformBundle:Default:locales.html.twig' %}
<div>
<p>{% trans%}return.to{% endtrans%} <a href="{{ path('about', { '_locale': app.request.get('_locale') }) }}">About</a></p>
</div>
{% endblock %}
-- locales.html.twig
<div class="langs">
<ul>
<li>
{% if app.request.get('_locale') == 'ru' %}
Русский
{% else %}
<a href="{{ path('locale', { 'locale': 'ru' }) }}">Русский</a>
{% endif %}
</li>
<li>
{% if app.request.get('_locale') == 'en' %}
English
{% else %}
<a href="{{ path('locale', { 'locale': 'en' }) }}">English</a>
{% endif %}
</li>
<li>
{% if app.request.get('_locale') == 'uk' %}
Украiнська
{% else %}
<a href="{{ path('locale', { 'locale': 'uk' }) }}">Украiнська</a>
{% endif %}
</li>
<li>
{% if app.request.get('_locale') == 'de' %}
Deutsch
{% else %}
<a href="{{ path('locale', { 'locale': 'de' }) }}">Deutsch</a>
{% endif %}
</li>
</ul>
</div>