from flask import render_template from app import app @app.route('/') @app.route('/index') defindex(): user = { 'nickname': 'Miguel' } # fake user return render_template("index.html", title = 'Home', user = user)
二.模版中的条件语句
控制语句,比如我们模版里面可以这么写
1 2 3 4 5 6 7 8 9 10 11 12
<html> <head> {% if title %} <title>{{title}} - microblog</title> {% else %} <title>Welcome to microblog</title> {% endif %} </head> <body> <h1>Hello, {{user.nickname}}!</h1> </body> </html>
这样我们在没有传title的时候会自动把题目改成Welcome to microblog
三.模版里的循环语句
我们先在视图文件里面写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defindex(): user = { 'nickname': 'Miguel' } # fake user posts = [ # fake array of posts { 'author': { 'nickname': 'John' }, 'body': 'Beautiful day in Portland!' }, { 'author': { 'nickname': 'Susan' }, 'body': 'The Avengers movie was so cool!' } ] return render_template("index.html", title = 'Home', user = user, posts = posts)
然后我们去templates里面的index.html里面去写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<html> <head> {% if title %} <title>{{title}} - microblog</title> {% else %} <title>microblog</title> {% endif %} </head> <body> <h1>Hi, {{user.nickname}}!</h1> {% for post in posts %} <p>{{post.author.nickname}} says: <b>{{post.body}}</b></p> {% endfor %} </body> </html>