简体   繁体   English

使用 FastAPI 渲染时将 Jinja2 模板作为 html 字符串传递?

[英]Pass Jinja2 template as html string while rendering using FastAPI?

My template is as follows:我的模板如下:

<!-- template1.html -->
<html>
<head>
    <title>Item Details</title>
</head>
<body>
    <p>{{ req }}</p>
</body>
</html>

To render the template I am using the following code:要呈现模板,我使用以下代码:

from fastapi import FastAPI
from fastapi.templating import Jinja2Templates

app = FastAPI()

template = Jinja2Templates(directory="templates")

@app.get("/list_items")
def home(request: Request):
    return template.TemplateResponse('template1.html',{"req": req})

@app.get("/", response_class=HTMLResponse)
async def read_items():
    return """
    <html>
      <head>
        <title></title>
      </head>
      <body>
        <form action="/list_items">
          <input type="text" placeholder="Search.." name="search">
          <button type="submit">Search</button>
        </form>
      </body>
    </html>
    """

But I do not want to use a separate folder with files for a simple template.但我不想使用带有文件的单独文件夹作为简单模板。 How do I pass the html text instead of the function TemplateResponse如何传递 html 文本而不是 function TemplateResponse

You can use HTMLResponse .您可以使用HTMLResponse Pass HTMLResponse as the parameter response_class of your route.HTMLResponse作为路由的参数response_class传递。

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get("/items", response_class=HTMLResponse)
def read_items():
    return """
    <html>
        <head>
            <title>Some HTML in here</title>
        </head>
        <body>
            <h1>Look ma! HTML!</h1>
        </body>
    </html>
    """

You can also override the response directly in your endpoint, by returning it.您还可以通过返回直接在端点中覆盖响应。

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get("/items")
def read_items():
    html_content = """
    <html>
        <head>
            <title>Some HTML in here</title>
        </head>
        <body>
            <h1>Look ma! HTML!</h1>
        </body>
    </html>
    """
    return HTMLResponse(content=html_content, status_code=200)

Update更新

Jinja2Templates.TemplateResponse expects as name parameter a filename that is pointing to the template your would like to return, and which lies in the Jinja2Templates directory you defined (eg, Jinja2Templates(directory="templates") ). Jinja2Templates.TemplateResponse需要一个文件名作为name参数,该文件名指向您要返回的模板,并且位于您定义的Jinja2Templates目录中(例如Jinja2Templates(directory="templates") )。 You can't pass the template contents to its place.您不能将模板内容传递到它的位置。 Jinja2Templates will attempt to retrieve the file you passed using the directory you defined earlier, see here -> here -> here . Jinja2Templates 将尝试使用您之前定义的目录检索您传递的文件,请参见此处-> 此处-> 此处 Hence, what you are asking, it doesn't seem to be possible;因此,您要问的是,这似乎是不可能的; further, there is nothing wrong with having a templates directory, even for small template files.此外,拥有templates目录并没有什么问题,即使对于小型模板文件也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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