Consider the following Jinja2 template snippet:
<a href="{{ url_for('/magic/{{ filename }}') }}">Click to see magic happen</a>
This code attempts to generate a URL to a route defined as:
@app.route('/magic/<filename>') def moremagic(filename): pass
However, the URL generated by the template snippet is incorrect because the {{ filename }} variable is not properly referenced within the url_for() function.
To resolve this issue, the extra set of curly braces within the url_for() function must be removed. This is because everything within the {{ ... }} in Jinja2 is a Python-like expression, and therefore, it is not necessary to use another {{ ... }} to reference variables.
The corrected code is as follows:
<a href="{{ url_for('moremagic', filename=name) }}">Click to see magic happen</a>
Here, the name variable is passed as an argument to the url_for() function, and the endpoint name moremagic is used instead of the URL path.
The above is the detailed content of How to Correctly Reference Template Variables within Jinja2's `url_for()` Function?. For more information, please follow other related articles on the PHP Chinese website!