python - 如何为 html 模板提供参数?
问题描述
我在quoted.html 中使用了四个参数,但是当我尝试从我的application.py 传递它们时,出现错误:TypeError:render_template() 采用1 个位置参数,但给出了4 个
@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
"""Get stock quote."""
#Look up for the stock symbol when user requires
if request.method == "POST":
#Check the symbol is none
if lookup(request.form.get("symbol")) == None:
return apology("The company's stock is not found!", 403)
#Show the stock result including name of the company and the stock price
else:
name = lookup(request.form.get("symbol"))["name"]
symbol = lookup(request.form.get("symbol"))["symbol"]
price = usd(lookup(request.form.get("symbol"))["price"])
return render_template("/quoted", name, symbol, price)
#Display the quote interface when user requires
else:
return render_template("quote.html")
这是我的quoted.html
{% extends "layout.html" %}
{% block title %}
Quote
{% endblock %}
{% block main %}
<form action="/quoted" method="get">
<fieldset>
<div class="form-group">
<h1> A share of {{ name }} ({{ symbol }}) costs {{ price }}</h1>
</div>
</fieldset>
</form>
{% endblock %}
这是查找函数的返回值
def lookup(symbol):
"""Look up quote for symbol."""
# Parse response
try:
quote = response.json()
return {
"name": quote["companyName"],
"price": float(quote["latestPrice"]),
"symbol": quote["symbol"]
}
解决方案
它render_template()
采用一个位置参数,即 html 文件。其余数据应作为关键字参数传递。
这是有关它的文档: https ://flask.palletsprojects.com/en/1.0.x/api/#flask.render_template
因此,您可以执行以下操作:
return render_template("quoted.html", name=name, symbol=symbol, price=price)
或者使用您的数据(字典、列表)创建一个数据结构并在您的 html 中使用它
推荐阅读
- chainlink - 在 Brownie 中分叉主网时如何处理链链接请求?
- amazon-web-services - 将 multipart/form-data 传递给 AWS API Gateway 以与 Lambda 集成
- php - 在 php 中使用 Mollie API 付款时出错
- angular - Ionic / Angular:在重新访问页面后多次调用EventListener
- python - Python - 如果内部发生错误
- c# - 从 MySQL 数据库中选择特定的行和列
- java - Docx4J 将 Docx 转换为带书签的 Pdf
- r - 等效于 R 中 Excel 中的索引匹配
- c++ - 将整数数组转换为位图并在 PictureBox 中显示(windows Forms C++/CLR)
- node.js - 错误 TS1086:无法在环境上下文中声明访问器