Jinja2 是一个现代的、设计友好的 Python 模板引擎,用于生成 HTML、XML 或其他标记语言。FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,基于 Python 3.7+ 的类型提示。结合 Jinja2 和 FastAPI 可以创建动态的 web 应用程序。
Jinja2:
FastAPI:
问题: 在使用 Jinja2 模板时,如何处理不同数量的输入项?
原因: 当需要渲染的页面依赖于不确定数量的数据时,直接在模板中硬编码可能会导致问题。
解决方法:
{% for item in items %}
来遍历列表中的每个元素。# FastAPI 视图函数
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from jinja2 import Template
app = FastAPI()
@app.get("/items/", response_class=HTMLResponse)
async def read_items():
items = ["Apple", "Banana", "Cherry"]
template = Template("""
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
""")
return template.render(items=items)
{% if condition %}
。# 在模板中添加条件判断
template = Template("""
<ul>
{% for item in items %}
{% if item != 'Banana' %}
<li>{{ item }}</li>
{% endif %}
{% endfor %}
</ul>
""")
# 传递字典
data = {
"fruits": ["Apple", "Banana"],
"vegetables": ["Carrot", "Broccoli"]
}
template = Template("""
<ul>
{% for category, items in data.items() %}
<h2>{{ category }}</h2>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
{% endfor %}
</ul>
""")
通过这些方法,可以灵活地处理不同数量和类型的输入项,确保模板渲染的正确性和效率。
领取专属 10元无门槛券
手把手带您无忧上云