flask - 使用烧瓶运行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>
我得到这样的输出:
解决方案
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)
推荐阅读
- sql - 如果 SQL IN 运算符中的字符串为空,则选择所有数据
- ios - Swift 如何使用表格视图单元格中的按钮更新子视图的标签和图像视图
- r - How to count number of rows in data.table using same condition on multiple columns in R
- vue.js - 在 VUE CLI 中使用 this.router.push 和跟踪动画结束进行转换
- php - 如何从具有值的行中选择数据
- javascript - 当您有一个重新加载页面的按钮时,如何使 javascript 将参数保留在 URL 中
- windows - Turtlebot3 Ros1 Windows 设置问题
- javascript - 将对象转换为打字稿中的列表列表
- python - 如何在 Pydantic 中创建多个约束类型
- javascript - 创建 Marker onClick 时,标记是偏移的,而不是鼠标光标所在的位置