【问题标题】:How to give arguments to a html template?如何为 html 模板提供参数?
【发布时间】:2021-06-24 06:36:28
【问题描述】:

我在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"]
        }

【问题讨论】:

  • 你使用什么框架来做模板和app.route 装饰器?

标签: python cs50 finance


【解决方案1】:

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 中使用它

【讨论】:

  • 谢谢。我知道 render_template() 接受一个参数,但就我而言,我尝试将其他参数传递给函数。我认为 render_template () 允许这样做。问题是我无法弄清楚我的代码有什么问题。
  • 它需要一个位置参数,其余的是关键字参数。 **文档中的上下文。您只传递位置参数,这是问题所在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-15
  • 1970-01-01
  • 2023-02-03
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
相关资源
最近更新 更多