Manually switch _locale in symfony 4(在 symfony 4 中手动切换 _locale)
问题描述
我完全无法在 Symfony 4 中手动切换 _locale
变量的解决方案.
I'm absolutely stuck in getting a solution to manually switch the _locale
variable in Symfony 4.
我遵循 这些步骤,但现在我完全不知道怎么做在导航部分制作一个简单的开关按钮.我还看了一个 this 问题,但这似乎是较旧的 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?
推荐答案
答案与this 答案在 Symfony 4 中不适用.从编辑 config 目录中的 services.yaml
文件开始.
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="e3sgYXNzZXQo"img/flags/' ~ locale ~ '.jpg') }}" alt="e3sgCmxvY2FsZSB9fQ==">
</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+ 编辑
根据下面 Charles 的回答,services.yaml
文件中的 locales 值应该用引号插入以避免无效的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 symfony 4 中手动切换 _locale
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
- SoapClient 设置自定义 HTTP Header 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Laravel 仓库 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01