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="{{ 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+ 编辑
根据下面 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
基础教程推荐
- 在多维数组中查找最大值 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01