Twig - 动态替换 GET 参数的值

问题描述 投票:0回答:3

有没有办法从树枝中替换 GET 参数值?

比如我在这个地址有一个页面:

http://localhost/app_dev.php/test/?param1=40&sort=name

在我的树枝中,我想建立 3 个这样的链接:

http://localhost/app_dev.php/test/?param1=40&sort=name 
http://localhost/app_dev.php/test/?param1=40&sort=address 
http://localhost/app_dev.php/test/?param1=40&sort=code 

现在我在 URL 的末尾再次添加了“&sort”参数,但这个解决方案实际上是一个“补丁”,它很糟糕!

<a href="{{app.request.requesturi}}&sort=address">address</a>

在这个例子中我只有 2 个参数,但实际上我有大约 6 个参数,因为生成的链接是通过提交 .

symfony parameters request twig
3个回答
31
投票

这应该可以解决您的问题:

{{ path(app.request.attributes.get('_route'),
   app.request.query.all|merge({'sort': 'address'})) }}

它获取当前路由和所有查询参数,这些参数在附加之前与您想要更新的参数合并。


2
投票

Symfony/Twig

path
函数接受可选参数。如果这些参数是路由的一部分,它们将由路由器处理,但如果不是,它们将作为 GET 参数传递。

所以,如果你对应的路线是,例如,

my_route
:

<a href="{{ path('my_route', {'param1':40, 'sort':'address'}) }}">address</a>

0
投票

如果你的路线有参数(如

/blog/post/{slug}
)并且你想自动检索它们你的
path()
应该是这样的,扩展@insertusernamehere答案:

<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge({'sort':'address')})) }}">address</a>

要保留所有查询参数并替换您需要的参数,请连接

merge
s:

<a href="{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')|merge(app.request.query.all)|merge({'sort':'address')})) }}">address</a>

此代码已在 Twig 3 上使用 Symfony 5.4/6.2 进行测试。

© www.soinside.com 2019 - 2024. All rights reserved.