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

问题描述 投票:1回答:1

我是第一次使用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

flask jinja2 python-3.7
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.