I am working on FastAPI and facing one challenge. I need to pass the variable in href url in html. Below my code:
main.py
@app.get('/', response_class=HTMLResponse)
def move(request: Request, row_: Optional[int] = None, col_: Optional[int] = None):
if row_ is not None and col_ is not None:
your_move = pl.click(row_, col_)
else:
your_move = pl.pcard
return templates.TemplateResponse('home.html', {'request': request, 'elements': your_move, 'count': pl.count} )
Note: Here, the query parameter is optional.
home.html
{% for row in elements|batch(4) %}
<div class="columns">
{% for column in row %}
<div class="column">
{% if column[0] == 'X' %}
<a href="'{{ url_for('move') }}' + '/?row_={{column[1]}}&col_={{column[2]}}' ">
<div id="example1"></div>
</a>
{% elif column[0] != 'X' %}
<div id="example2">
<h1 style="width:100%; text-align: center; padding: -20px; font-size: 5em;">{{ column[0] }}</h1>
</div>
{% endif %}
</div>
{% endfor %}
</div>
{% endfor %}
Here, I tried for url_for('move') in HTML, but it's not working when passing query string parameters. How to achieve the same. I tried one more way:
<a href="'{{ url_for('move', row_={{column[1]}}, col_={{column[2]}}) }}">
Still, both methods do not work for me. Kindly suggest.
You never nest Jinja {{...}}
markers. You want something like:
<a href="'{{ url_for('move', row_=column[1], col_=column[2]) }}">
You get the starlette.routing.NoMatchFound error, since url_for() receives path parameters, not query parameters ( as yet ). So, you are passing two params (ie, row_ and col_) that are expected to be path parameters (such a route cannot be found in your code), but are actually query params. Please have a look at this answer on how to call FastAPI routes from within jinja2 templates, and pass query params.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.