php - Manually switch _locale in symfony 4
问题描述
I'm absolutely stuck in getting a solution to manually switch the _locale
variable in Symfony 4.
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..
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?
解决方案
答案与这个在 Symfony 4 中不适用的答案略有不同。从编辑services.yaml
config 目录中的文件开始。
{# 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' %}
编辑 Symfony 4.3.4+
根据下面查尔斯的回答,services.yaml
文件中的语言环境值应该用引号插入以避免无效的 YAML 错误:
{# project/config/services.yaml}
# ...
parameters:
# ...
app_locales: [nl_NL, en_EN]
twig:
# ...
globals:
locales: "%app_locales%"
# ...
推荐阅读
- sql - 将列中的所有值设置为等于 Postgres 中窗口上的第一个非空值
- html - Vue.js 中未打印索引数量
- polly - 将 Polly 重试策略添加到模拟的 HttpClient?
- algolia - 如何清除 algolia 的搜索查询缓存?
- java - 使用 Firebase 刷新列表的最佳方法是什么
- flutter - 如何在 Flutter 中获取 Asset 对象的路径?
- bash - 无法在文本文件上使用 SED 命令删除撇号
- git - 仅当前分支的 git 日志 - 不指定它来自哪里(master..)
- intellij-idea - 无论我在 Intellij 上做什么,JavaFX 运行时版本都不会更新
- python - 在 Python 中使用 awk 在文件中插入文本