语言切换不改变当前页面 [英] language switching without changing the current page

查看:21
本文介绍了语言切换不改变当前页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多语言 Symfony2 项目中使用 twig 进行模板化.layout.html.twig 中有一个语言切换器

I use twig for templating in a multilingual Symfony2 project. There is a language switcher in layout.html.twig

我希望用户可以通过单击语言链接在不更改当前页面的情况下切换语言.我编写了以下代码,它只为静态页面执行任务.由于语言链接只是将locale传递给路由,如果涉及额外的必需参数,显然会抛出异常:route has some missing required parameters

I want the user can switch languages without changing the current page by clicking the language link. I have written the following code which just does duty for static pages. Since the language links just pass locale to the route, in case of involvement of additional required parameters, it obviously throws the exception: route has some missing mandatory parameters

<ul id="lang">
    <li><a href="{{ path(app.request.attributes.get('_route'), {_locale: 'az'}) }}">AZ</a></li>
    <li><a href="{{ path(app.request.attributes.get('_route'), {_locale: 'en'}) }}">EN</a></li>
</ul>

推荐答案

您可以通过 .get('_route_params')将它们与您想要的语言环境合并:

<ul class="lang-menu">
  <li><a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale': 'ca'})) }}">Català</a></li>
  <li><a href="{{  path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale': 'en'}))}}">English</a></li>
</ul>

这篇关于语言切换不改变当前页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆