38

So let's say I have a template with a couple of links, the links will be like this:

<a class='btn btn-primary' href='/?chart=new_chart&chart=other_chart'>View Summary</a>

However, most of the times when I have done links or included resources, I have used the following syntax:

<script src="{{ url_for('static', filename='some_silly_js') }}"></script>

is it possible to do a url_for with query parameters? Something like:

<a href="{{ url_for('stats', query_params={chart: [new_chart, other_chart]}) }}>View More</a>

2 Answers 2

60

Any extra keyword parameters passed to url_for() which are not supported by the route are automatically added as query parameters.

For repeated values, pass in a list:

<a href="{{ url_for('stats', chart=[new_chart, other_chart]) }}>View More</a>

Flask will then:

  1. find the stats endpoint
  2. fill in any required route parameters
  3. transform any remaining keyword parameters to a query string

Demo, with 'stats' being the endpoint name for /:

>>> url_for('stats', chart=['foo', 'bar'])
'/?chart=foo&chart=bar'
Sign up to request clarification or add additional context in comments.

Comments

2

As per the documentation:

Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments.

I have tried this and it works as per the documentation

redirect(url_for('face_id_detail', faceid=faceid, name=faceidtag))

Note: faceid is the parameter in the method && name is not in the method parameters so it is appending to querystring.

The method signature for face_id_detail is:

@app.route('/faceids/<faceid>')
def face_id_detail(faceid):
    # the method code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.