上一章节是做到了在本地浏览器上打印出hello,world
如果你要更加复杂,可以像下面一样在return结果里添加内容
但是!!简单的几句话你可以这么写,要是整的一个网页,你可没法把代码都拖在return后面吧
所以,后面引入了模板功能
模板:
模板的位置放在templates文件夹下面,一般是html文件,我们把index.html改动成如下样式
<html>
<head>
<title>{{title}} - microblog</title>
</head>
<body>
<h1>Hello, {{user.nickname}}!</h1>
</body>
</html>
其中: {{}}表示这是一个变量,可以根据用户在模块端给予的参数的不同,进行调整
下面的程序就是调用了 render_template模板
from flask importrender_template
from app importapp
@app.route('/')
@app.route('/index')
def index():
user = {'nickname': 'Miguel'} # fake user
return render_template("index.html",
title = 'Home',
user = user) #这里模块里的第一个user指的是html里面的变量user,而第二个user指的是函数index里面的变量user
说白了,其实render_template的功能是对先引入index.html,同时根据后面传入的参数,对html进行修改渲染。
然后,render_template模板其实也是接受控制语句的,修改后的index.html如下:
<html>
<head>
{% if title %} #{% %}这样代表控制语句,意思是如果有传入title变量,则显示title-microblog
<title>{{title}} - microblog</title>
{% else %}
<title>Welcome to microblog</title> #如果没有传入参数,则显示welcome to microblog
{% endif %} #这里大不同!!HTML里面的逻辑语句,需要用{% endif %} 来结束逻辑语句
</head>
<body>
<h1>Hello, {{user.nickname}}!</h1>
</body>
</html>
我们再来看一个循环语句的修改版的views.py和index.html
def index():
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)
<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>
注意,这里的访问都是用点来继承的,比如post.author.nickname
<head>
{% if title %}
<title>{{title}} - microblog</title>
{% else %}
<title>microblog</title>
{% endif %}
</head>
<body>
<div>Microblog: <a href="/index">Home</a></div>
<hr>
{% block content %}{% endblock %}
</body>
</html>
{% block content %}
<h1>Hi, {{user.nickname}}!</h1>
{% for post in posts %}
<div><p>{{post.author.nickname}} says: <b>{{post.body}}</b></p></div>
{% endfor %}
{% endblock %}