如何通过flask将python变量传递给我的模板?

问题描述

我用 Flask 制作了一个 Web 应用程序。我想将一个变量值传递给我的模板,以设置属性

在蟒蛇中:

web_size="100%"

@app.route('/')
def home():
  return render_template("web.html")

def size():
  return "50px"

在 html5 文件中,我使用了:

width: {{url_for('size')}};

我做错了什么?以及如何使用 orl_for 命令?我想我什至不明白它是如何工作的。

解决方法

要将 Python 变量传递给 Flask 模板,请执行以下操作:

在视图中首先声明 Python 变量。然后,将变量作为 render_template 方法中的参数传递给模板:

@app.route('/',methods={'GET'})
def home():
    title = "Frankenstein"
    return render_template('index.html',book_title=title )

然后,要在 index.html 模板中显示变量,请使用花括号:

<h3>The book named "{{book_title}}" </h3>
,

您尚未将数据传递到 html 表中。例如:

message = 'Hello!'
return render_template('index.html',value= message)