首页 > 解决方案 > 使用烧瓶运行python时的部分输出

问题描述

我第一次使用烧瓶,正在做一些来自 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>

我得到这样的输出:

输出

标签: flaskjinja2python-3.7

解决方案


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)

推荐阅读