Manually switch _locale in symfony 4

喜欢而已 提交于 2019-12-14 04:20:39

问题


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?


回答1:


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' %}

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%"
        # ... 



回答2:


I don't have enough reputation to comment, so I'll add an answer.

The above code gives an error (at least in Symfony 4.3.4). Error:

The file "[...]config/services.yaml" does not contain valid YAML: The reserved indicator "%" cannot start a plain scalar; you need to quote the scalar at line 40 (near "locales: %app_locales%")

So to fix this the services.yaml should be like this:

{# project/config/services.yaml}

# ...
parameters:
    # ...
    app_locales: [nl_NL, en_EN]

twig:
    # ...
    globals:
        locales: "%app_locales%"
        # ...


来源:https://stackoverflow.com/questions/51597719/manually-switch-locale-in-symfony-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!