在symfony 4中手动切换_locale [英] Manually switch _locale in symfony 4
问题描述
我绝对无法获得一种在Symfony 4中手动切换_locale
变量的解决方案.
I'm absolutely stuck in getting a solution to manually switch the _locale
variable in Symfony 4.
我遵循了这些步骤,但是现在我完全不知道如何在nav部分中制作一个简单的切换按钮.我还看了一个这个问题,但这似乎是一个较旧的Symfony版本..
I followed these steps, but now I have absolutely no idea how to make a simple switch button in the nav section. I also took a look a this question, but this seems to be an older Symfony version..
任何人都可以帮助我从这个黑洞中爬出来,向我解释如何集成一个简单的_locale
开关按钮,或者至少将我指向正确的方向吗?
Can anyone please help me climb out of this dark hole and explain to me how I can integrate a simple _locale
switch button, or at least point me in the right direction?
推荐答案
The answer is slightly different from this answer which is not applicable in Symfony 4. Start with editing the services.yaml
file in the config directory.
{# project/config/services.yaml}
# ...
parameters:
# ...
app_locales: [nl_NL, en_EN]
twig:
# ...
globals:
locales: %app_locales%
# ...
然后添加一个模板,以将切换按钮集成到基本模板中的某个位置.
Then add a template to integrate the switch button somewhere in your base template.
{# 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 %}
最后将这个全新的模板集成到您的基本模板中.
And finally integrate this brandnew template in your base template.
{# project/templates/base.html.twig #}
{% include '_locale_switcher.html.twig' %}
编辑Symfony 4.3.4 +
根据下面的查尔斯回答,在services.yaml
文件中的语言环境值应插入引号,以避免无效的YAML错误:
EDIT for Symfony 4.3.4+
As per the answer of Charles beneath, the locales value in services.yaml
file should be inserted with quotes to avoid an unvalid YAML error:
{# project/config/services.yaml}
# ...
parameters:
# ...
app_locales: [nl_NL, en_EN]
twig:
# ...
globals:
locales: "%app_locales%"
# ...
这篇关于在symfony 4中手动切换_locale的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!