Ask Your Question

How can the value of a GET parameter be dynamically replaced using Twig?

asked 2021-05-16 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-01-24 04:00:00 +0000

bukephalos gravatar image

To dynamically replace the value of a GET parameter using Twig, you can use the app.request.query.get method along with the url_query_append filter.

For example, let's say you have a GET parameter named page and you want to replace its value with the Twig variable newPage. You can use the following code:

{% set newPage = 2 %}

<a href="{{ app.request.uri ~ '?' ~ app.request.query|merge({'page': newPage})|url_query_append }}">Next Page</a>

In this code, we first set the newPage variable to 2 (which could be any dynamic value). Then, we use the app.request.uri variable to get the current URL and append a question mark ? to it.

Next, we use the app.request.query variable to get an array of all GET parameters in the current URL. We merge this array with a new array that has the page parameter set to the value of newPage.

Finally, we use the url_query_append filter on this new array to generate a properly-formatted GET parameter string and append it to the current URL.

This will generate a link that goes to the current page with the page parameter set to the value of newPage.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools


Asked: 2021-05-16 11:00:00 +0000

Seen: 7 times

Last updated: Jan 24 '22