我会在现有网站中添加一些指向不同语言环境版本的链接。它工作得很好,但它非常难看^^
<li>
<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge(app.request.query.all|merge({_locale: 'es'}))) }}">
<img src="{{ asset('img/flags/es.jpg') }}" alt="es">
</a>
</li>
<li>
<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge(app.request.query.all|merge({_locale: 'fr'}))) }}">
<img src="{{ asset('img/flags/fr.jpg') }}" alt="fr">
</a>
</li>
你有更好的想法吗?
答案 0 :(得分:7)
您可能需要在许多页面和/或多个项目中使用此功能。这是基于我在某些方面使用的可能方式:
# app/config/config.yml
# ...
parameters:
# ...
app_locales: [en, es, fr]
twig:
# ...
globals:
locales: %app_locales%
# ...
然后是一个持有标志的模板:
{# app/Resources/views/includes/_flags.html.twig #}
{% set route = app.request.attributes.get('_route') %}
{% set route_params = app.request.attributes.get('_route_params') %}
{% set params = route_params|merge(app.request.query.all) %}
{# You may want to not print a flag/link for current view, the "if" here let you handle it #}
{% for locale in locales if locale != app.request.locale %}
<li>
<a href="{{ path(route, params|merge({ _locale: locale })) }}">
<img src="{{ asset('img/flags/' ~ locale ~ '.jpg') }}" alt="{{ locale }}">
</a>
</li>
{% endfor %}
最后在任何视图中包含标志:
{# app/Resources/views/base.html.twig #}
{% include 'includes/_flags.html.twig' %}