Twig 链接到当前路线但更改区域设置 [英] Twig links to current route but changing locale
本文介绍了Twig 链接到当前路线但更改区域设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我会在现有网站中添加一些指向不同语言环境版本的链接.它工作得很好,但它很丑^^
I would add some links to differents locales versions in my existing website. It works quite well but it is pretty ugly^^
<li>
<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge(app.request.query.all|merge({_locale: 'es'}))) }}">
<img src="{{ asset('img/flags/es.jpg') }}" alt="es">
</a>
</li>
<li>
<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge(app.request.query.all|merge({_locale: 'fr'}))) }}">
<img src="{{ asset('img/flags/fr.jpg') }}" alt="fr">
</a>
</li>
你有更好的想法吗?
推荐答案
您可能在许多页面和/或多个项目中都需要这个.根据我在某些方面使用的方法,这是一种可能的方法:
You may need this in many pages and/or more than one project. Here's a possible way based on what I've been using in some:
# app/config/config.yml
# ...
parameters:
# ...
app_locales: [en, es, fr]
twig:
# ...
globals:
locales: %app_locales%
# ...
然后是一个拿着旗帜的模板:
Then a template for holding flags:
{# app/Resources/views/includes/_flags.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 %}
最后在任何视图中包含标志:
Finally include flags in any view:
{# app/Resources/views/base.html.twig #}
{% include 'includes/_flags.html.twig' %}
这篇关于Twig 链接到当前路线但更改区域设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文