flask学习(2)模版

首先先确认一下文件结构

1
2
3
4
5
6
7
8
9
10
microblog\
flask\
virtual environment files
app\
static\
templates\
__init__.py
views.py
tmp\
run.py

然后如果我们在写站的时候直接写html的话就需要处理转义的问题,而这就涉及到程序的安全问题了,所以flask就给我们配置好了jinja模版.

一.模版的使用

模版可以帮我们把网页的布局和逻辑分开 然后我们把动态的内容放在{{...}}里面就ok 比如我们写(app/templates/index.html)

1
2
3
4
5
6
7
8
<html>
<head>
<title>{{title}} - microblog</title>
</head>
<body>
<h1>Hello, {{user.nickname}}!</h1>
</body>
</html>

然后再

1
2
3
4
5
6
7
8
9
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
def index():
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
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)

然后我们去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>

这样就可以进行快速渲染了

最后,模版继承

抽象的说不太好说,直接用例子说明吧 首先templates里面写一个(app/templates/base.html)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html>
<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>

然后我们在(app/templates/index.html)里面去写

1
2
3
4
5
6
7
{% extends "base.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 %}

这就相当于把index.html的block content到endblock中间的东西放到base.html的block content和endblock中间然后返回base.html给用户,这就是模版的继承 终于前面django的坑被填上了....