I have implemented the following language switcher:

<ul id="language-selector">
    {% if path(app.request.attributes.get('_route')) == '/' %}
        <li><a href="{{ path("homepage", {"_locale": "es"}) }}">ES</a></li>
        <li><a href="{{ path("homepage", {"_locale": "en"}) }}">EN</a></li>
        <li><a href="{{ path("homepage", {"_locale": "it"}) }}">IT</a></li>
    {% else %}
        <li><a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge({'_locale': 'es'})) }}">ES</a></li>
        <li><a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge({'_locale': 'en'})) }}">EN</a></li>
        <li><a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge({'_locale': 'it'})) }}">IT</a></li>
    {% endif %}
</ul>

I'm using JMSi18nRoutingBundle for translating the urls. It works fine but when it renders a view which has a parameter in the url, the following error appears:

An exception has been thrown during the rendering of a template ("Some mandatory
parameters are missing ("id") to generate a URL for route
"es__RG__myapp_mybundle_myaction_edit".") in
MyAppMyBundle:Default:includes/myView.html.twig at line 21.
有帮助吗?

解决方案

Use following condition to check for homepage

{% if app.request.attributes.get('_route') == 'homepage' %}

instead of

{% if path(app.request.attributes.get('_route')) == '/' %}

Explanation:

When you are accessing an URL which required parameter(s), your code in if statement path(app.request.attributes.get('_route')) generates the error. As your home page route is defined as homepage, only checking the _route attribute will be enough to determine that you are accessing the homepage.

Happy coding!!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top