Twig - dynamically replace GET parameter's value
Asked Answered
S

3

7

Is there a way to replace a GET parameter value from twig?

For example, I have a page at this address:

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

And in my twig I want to build 3 links like this:

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 

For now I added the "&sort" parameter once again at the end on the URL, but this solution is actually a "patch" and it sucks!

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

In this example I only have 2 parameters, but in reality I have around 6 parameters, because the link that's generated it's obtained by submitting a .

Springs answered 12/3, 2013 at 13:36 Comment(2)
I don't understand the question. Could you explain in more detail?Aer
well... I need to get the current URL and then replace the value of an existent parameter. In the example provided I want to rebuild the URL with a different value for "sort"Springs
M
31

This should solve your problem:

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

It gets the current route and all query parameters which are merged with the one you like to update before they are appended.

Mudstone answered 12/3, 2013 at 14:14 Comment(1)
you... I like you ^^Polio
B
2

Symfony/Twig path function accept optional params. If these params are part of the route, they're handled by router but if they're not, they are passed as GET parameters.

So, if your corresponding route is, for example, my_route :

<a href="{{ path('my_route', {'param1':40, 'sort':'address'}) }}">address</a>
Boru answered 12/3, 2013 at 14:3 Comment(2)
but what if I have a list of 6 parameters? I need to build the link for all the params? The link generated is obtain by submitting a <form>...Springs
@Mudstone has your answer. It keeps request parameters and replace only those you want to be changed.Boru
C
0

If your route has params (like /blog/post/{slug}) and you want automatically retrieve them your path() should be like this, extending @insertusernamehere answer:

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

To keep all query parameters and replace the ones you need, concatenate the merges:

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

This code has been tested with Symfony 5.4/6.2 on Twig 3.

Cheetah answered 31/3, 2023 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.