简体   繁体   中英

How to pass parameter to path in url_for FastAPI?

I am an absolute newbie to FastAPI and faced a pretty strange problem. While trying to display an image by its name (which is the same as id), I just cannot pass the name to the template. To make it clear, everything works fine if I just hardcode the id, but the question is how to pass it automatically? Here is my main.py:

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")


templates = Jinja2Templates(directory="templates")


@app.get("/items/{id}", response_class=HTMLResponse)
async def read_item(request: Request, id: str):
    return templates.TemplateResponse("item.html", {"request": request, "id": id})

And here is my template.

<html>
<head>
    <title>Item Details</title>
    <link href="{{ url_for('static', path='/css/styles.css') }}" rel="stylesheet">
</head>
<body>
    <h1>Item ID: {{ id }}</h1>
    <img src="{{ url_for('static', path='/qr-codes/{{ id }}.png') }}"/>
</body>
</html>

But this line: <img src="{{ url_for('static', path='/qr-codes/{{ id }}.png') }}"/> doesn't work as {{ id }} isn't seen as a parameter.

So my question is how can I pass my parameter to path in url_for? Thanks for every responce!

In item.html, change the img src path value to the below:

<img src="{{ url_for('static', path='/qr-codes/'+ id + '.png') }}" />

Request URL:

http://localhost:8000/items/1

OpenApi (Swagger) Output

<h1>Item ID: 1</h1>
<img src="http://localhost:8000/static/qr-codes/1.png" />

Note: Concatenate the string using '+' gives the formatted value

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM