我绝对无法获得一种在Symfony 4中手动切换_locale
变量的解决方案。
我遵循了these steps,但是现在我完全不知道如何在nav部分中制作一个简单的切换按钮。我也看了一个this问题,但这似乎是一个较旧的Symfony版本。.
有人可以帮助我从这个黑洞中爬出来,向我解释如何集成一个简单的_locale
开关按钮,或者至少将我的方向指向正确吗?
答案 0 :(得分:2)
我没有足够的声誉来发表评论,所以我将添加一个答案。
上面的代码给出了一个错误(至少在Symfony 4.3.4中)。错误:
The file "[...]config/services.yaml" does not contain valid YAML: The reserved indicator "%" cannot start a plain scalar; you need to quote the scalar at line 40 (near "locales: %app_locales%")
要解决此问题,services.yaml
应该像这样:
{# project/config/services.yaml}
# ...
parameters:
# ...
app_locales: [nl_NL, en_EN]
twig:
# ...
globals:
locales: "%app_locales%"
# ...
答案 1 :(得分:0)
答案与this答案略有不同,后者在Symfony 4中不适用。首先在配置目录中编辑services.yaml
文件。
{# project/config/services.yaml}
# ...
parameters:
# ...
app_locales: [nl_NL, en_EN]
twig:
# ...
globals:
locales: %app_locales%
# ...
然后添加一个模板,以将切换按钮集成到基本模板中的某个位置。
{# project/templates/_locale_switcher.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 %}
最后将这个全新的模板集成到您的基本模板中。
{# project/templates/base.html.twig #}
{% include '_locale_switcher.html.twig' %}
答案 2 :(得分:0)
这是在最新的 symfony 4 版本上对我有用的内容
services.yaml:
parameters:
locale: 'en'
app_locales: en|fr
twig:
globals:
locales: '%app_locales%'
语言环境模板:
{# project/templates/_locale_switcher.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|split('|') %}
{% 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>
{% endif %}
{% endfor %}