问题
There is a multilingual website built in Symfony2. In the base layout, there is language switch something like this:
<a href="{{ path(app.request.attributes.get('_route'), {_locale: 'en'}) }}">EN</a>
<a href="{{ path(app.request.attributes.get('_route'), {_locale: 'fr'}) }}">FR</a>
This works fine switching languages without changing the current page. However, if there are other parameters it throws an exception because of 'missing mandatory parameters'. How to overcome this?
回答1:
You could do something like :
<a href="{{ path(app.request.attributes.get('_route'), app.request.query.all|merge({'_locale': 'en'})) }}">EN</a>
<a href="{{ path(app.request.attributes.get('_route'), app.request.query.all|merge({'_locale': 'fr'})) }}">FR</a>
What this does is merge the _locale parameter with the existing query parameters.
回答2:
This is my solution, work with Symfony 2.2 to 2.5
<a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale': 'en'})) }}">English</a>
<a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale': 'fr'})) }}">Français</a>
<a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale': 'es'})) }}">Español</a>
This is my solution, work with Symfony 2.0 to 2.1
<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge({'_locale': 'en'})) }}">English</a>
<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge({'_locale': 'fr'})) }}">Français</a>
<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge({'_locale': 'es'})) }}">Español</a>
来源:https://stackoverflow.com/questions/11203852/filling-all-mandatory-parameters