您已经看到了Jinja2在呈现过程中如何用实际值替换占位符,但这只是Jinja2在模板文件中支持的众多强大操作之一。例如,模板还支持在{%…%}块。下一个版本的index.html模板增加了一个条件语句:
app/templates/index.html:
- <!doctype html>
- <html>
- <head>
- {% if title %}
- <title>{{ title }} - Microblog</title>
- {% else %}
- <title>Welcome to Microblog!</title>
- {% endif %}
- </head>
- <body>
- <h1>Hello, {{ user.username }}!</h1>
- </body>
- </html>
现在模板更聪明了。如果视图函数忘记为标题占位符变量传递一个值,那么模板将提供一个默认的标题,而不是显示一个空标题。您可以通过在视图函数的render_template()调用中删除title参数来尝试这个条件是如何工作的。
登录的用户可能希望在主页中看到已连接用户的最新帖子,因此我现在要做的是扩展应用程序以支持这一点。
再一次,我将依靠方便的伪对象技巧来创建一些用户和一些帖子来显示:
app/routes.py:
- from flask import render_template
- from app import app
-
- @app.route('/')
- @app.route('/index')
- def index():
- user = {'username': 'Miguel'}
- posts = [
- {
- 'author': {'username': 'John'},
- 'body': 'Beautiful day in Portland!'
- },
- {
- 'author': {'username': 'Susan'},
- 'body': 'The Avengers movie was so cool!'
- }
- ]
- return render_template('index.html', title='Home', user=user, posts=posts)
为了表示用户帖子,我使用了一个列表,其中每个元素都是一个具有作者和正文字段的字典。当我真正实现用户和博客文章时,我将尽量保留这些字段名,以便在引入真正的用户和文章时,使用这些假对象设计和测试主页模板所做的所有工作将继续有效。