我想用 python 函数的结果填充/更新 index.html 中的 div 区域,但我不知道该怎么做。我知道还有其他几个具有类似主题的问题,但我无法成功解决它们,因为它们太具体了。我正在为此抓狂。
会有这么好的人来指导我吗?
这是 main.py 中的一个函数:
@app.route('/')
def index():
return render_template('index.html')
@app.route('/stat/')
def stat():
a = 2
b = 10
return(str(a) + ' is not ' + str(b))
Run Code Online (Sandbox Code Playgroud)
这是index.html:
<body>
<form action="/stat/">
<button type="submit" id="btn1" class="btn btn-primary btn-sm">check stat</button>
</form>
<div id="stat_content"></div>
</body>
Run Code Online (Sandbox Code Playgroud)
正如 @S3DEV 指出的,您需要通过附加参数将字符串传递给模板。例如,我们可能会这样做:
@app.route('/stat/', methods=['GET', 'POST']) # EDIT
def stat():
a = 2
b = 10
text = f"{a} is not equal to {b}"
return render_template("index.html", text=text)
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我们设置text为要传递给模板的字符串。在模板中,我们将能够以text.
现在,当index.html渲染时,它将查找text从 Flask 应用程序传入的变量。这是由Jinja 2负责的,它是 Flask 使用的渲染引擎。
<div id="stat_content">
{% if text %}
<h2>No text to show</h2>
{% else %}
<h2>{{ text }}</h2>
{% endif %}
</div>
Run Code Online (Sandbox Code Playgroud)
使用带有大括号的 Jinja 2 语法,我们首先检查变量text是否存在;如果它不存在,我们将呈现消息“没有可显示的文本”。当我们第一次路由到"/"Flask 应用程序的默认主路由时,就会发生这种情况。
然而,一旦用户填写了表单,他们将被重定向到"/stat/",此时我们将生成它并通过函数调用text将其传递回。然后,当 Jinja 2 渲染 时,它将看到从 Flask 应用程序传递过来的 并显示该消息,即 2 不等于 10。index.htmlrender_template("index.html", text=text)index.htmltext
| 归档时间: |
|
| 查看次数: |
6001 次 |
| 最近记录: |