我第一次使用烧瓶,是从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>
我得到这样的输出:
答案 0 :(得分:2)
渲染模板时您没有通过posts
!在posts=posts
中添加render_template
!
赞:
@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)