gpt4 book ai didi

flask - 使用flask运行python时的部分输出

转载 作者:行者123 更新时间:2023-12-02 20:52:20 25 4
gpt4 key购买 nike

我是第一次使用 Flask,正在从 youtube 上做一些教程。我重新检查了代码,但没有解决。 “for”中最后代码的输出未打印

Python 代码:

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def hello():
return 'Hello, World!'


@app.route('/about')
def about():
return 'The About Page'


@app.route('/blog')
def blog():
posts = [{'title': 'Technology in 2019', 'author': 'Sreeram'},
{'title': 'Expansion of oil in Russia', 'author': 'Bob'}]
return render_template('blog.html', author='bob', sunny=True)


@app.route('/blog/<string:blog_id>')
def blogpost(blog_id):
return 'This is blog post number' + (blog_id)


if __name__ == '__main__':
app.debug = True
app.run()

html代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>blog</title>
</head>
<body>
<h2> Welcome to this blog! </h2>
<p> I am Sreeram, the author of this blog </p>
{% if sunny %} -->
<p> Today it is sunny</p> -->
{% else %} -->
<p> Today it is rainy</p> -->
{% endif %} -->

{% for post in posts %}
<h2>{{post.title}}</h2>
<h3>Author : {{post.author}}</h3>
{% endfor %}

</body>
</html>

我得到这样的输出:

Output

最佳答案

渲染模板时您没有传递posts!在 render_template 中添加 posts=posts!

像这样:

@app.route('/blog')
def blog():
posts = [{'title': 'Technology in 2019', 'author': 'Sreeram'},
{'title': 'Expansion of oil in Russia', 'author': 'Bob'}]
return render_template('blog.html', author='bob', sunny=True, posts=posts)

关于flask - 使用flask运行python时的部分输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55939507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com