I access a page with the path /mypage?a=1&b=1&c=1
. I want to create a link to a similar url, with some parameters changed: /mypage?a=1&b=2&c=1
, b changed from 1 to 2. I know how to get the current arguments with request.args
, but the structure is immutable, so I don't know how to edit them. How do I make a new link in the Jinja template with the modified query?
The value of a parameter can be updated with the set() method of URLSearchParams object. After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.
set('PARAM_HERE', VALUE_HERE); history. pushState(null, '', url); This will preserve everything about the URL and only change or add the one query param. You can also use replaceState instead of pushState if you don't want it to create a new browser history entry.
get() method. Using the params property we can pass parameters to the HTTP get request. Either we can pass HttpParams or an object which contains key value pairs of parameters.
To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.
Write a function that modifies the current url's query string and outputs a new url. Add the function to the template globals using your Flask app's template_global
decorator so that it can be used in Jinja templates.
from flask import request
from werkzeug.urls import url_encode
@app.template_global()
def modify_query(**new_values):
args = request.args.copy()
for key, value in new_values.items():
args[key] = value
return '{}?{}'.format(request.path, url_encode(args))
<a href="{{ modify_query(b=2) }}">Link with updated "b"</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With