在 symfony 4 中手动切换 _locale

2022-01-22 00:00:00 locale php symfony twig

我完全无法在 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%"
        # ... 

相关文章