Flask url_for() with arguments
I think, you have to learn information about creating variable url with flask and jinja.
Example of variable url.
HTML
<ul>
{% for x in lk1 %}
<li><a href="{{ url_for('bookPage', title=x[2] }}">{{ x[2] }} (by) {{ x[3] }} (year) : {{ x[4] }}</a></li>
{% endfor %}
</ul>
Python
@app.route('/books/<title>' )
# the name of this function have to be used in
# url_for ('nameOfFunction', name_of_variable_part_of_url=some_internal_variable)
def bookPage(title):
# code, that will creat yourlist
# book.html - template for book
# listofvariables - variables for book's page
#
return render_template ("book.html", listofvariables=yourlist)
Link to a similar question: Reference template variable within Jinja expression
Update: to use many variables in an url you have to change html and python.
Html:
<a href="{{ url_for('bookPage', title=x[2], heading=x[3]) }}">all your text </a>
Python:
@app.route('/books/<title>-<heading>' )
def bookPage(title, heading):
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
I'm learning Flask and I got stuck here.
How to make links for searched results with arguments ( parameter ) ?
My app searches for books and renders them on an HTML page using Flask and Jinja2 along with HTML only.
So my HTML has only this function:
<ul> {% for x in lk1 %} <li><a href="{{ url_for('bookPage'}}">{{ x[2] }} (by) {{ x[3] }} (year) : {{ x[4] }}</a></li> {% endfor %} </ul>
where
lk1
is the list of books gathered by Flask from SQL andx
are the raw info from SQL databaseNow in page
bookpage.html
it's empty I need to pass arguments with the URL so I can render them on the page or fetch the rest of info about this book and render it in the book page also if you could help me understand how to make URL of the book title which is according to my code it's{{ x[2] }}
I saw ppl doing something like<url_titl>
but I don't know how it worksThank you!