2.3.1 if判断语句
(1)语法:if的使用和python中的使用相差无几。
{% if xxx %}
{% elif xxx %}
{% else %}
{% endif %}
(2)示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
{% if user and user.age > 18 %} {# 若存在user且其年龄大于18 #}
<a href="#">{{ user.username }}</a>
<a href="#">注销</a>
{% else %}
<a href="#">登录</a>
<a href="#">注册</a>
{% endif %}
</body>
</html>
@app.route('/<is_login>/')
def index(is_login):
if is_login=='1':
user = {
'username' : u'张三',
'age' : 21
}
return render_template('index.html', user= user)
# 已经注册则传进去参数
else:
return render_template('index.html')
# 没有注册则直接渲染
2.3.2 for循环语句及遍历字典和列表
* 字典遍历:语法和python一样,可以使用items()
、keys()
、values()
、iteritems()
、iterkeys()
、itervalues()
{% for k,v in user.items() %}
<p>{{ k }}:{{ v }}</p>
{% endfor %}
{% for label,link in links.items() %}
{% if not loop.first %}|{% endif %} {# 如果不是第一次循环,输出一个竖杠。 loop.first是测试函数,测试函数的相关说明见下面的补充部分#}
<a href="{{ link }}">{{ label }}</a>
{% endfor %}
# for遍历字典
@app.route('/')
def index():
# 定义一个字典
user = {
'username' : u'李四',
'age' : 21
}
links = {
'百度':'www.baidu.com',
'谷歌':'www.google.com'
}
return render_template('index.html',user=user,links=links)
* 列表遍历:语法和python一样
{% for website in websites %}
<p>{{ website }}</p>
{% endfor %}
# for遍历列表
@app.route('/')
def index():
websites = ['www.baidu.com','www.google.com']
return render_template('index.html',websites=websites)
完整小实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<p>综合运用列表和字典的模板文件</p>
<table>
<thead>
<th>书名</th>
<th>作者</th>
<th>价格</th>
</thead>
<tbody>
{% for book in books %}
<tr>
<td>{{ book.name }}</td>
<td>{{ book.author }}</td>
<td>{{ book.price }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
#encoding: utf-8
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def index():
books = [
{
'name' : u'西游记',
'author' : u'吴承恩',
'price' : 120
},
{
'name': u'三国演义',
'author': u'罗贯中',
'price': 114
},
{
'name': u'红楼梦',
'author': u'曹雪芹',
'price': 96
},
{
'name': u'水浒传',
'author': u'施耐庵',
'price': 101
}
]
return render_template('index.html', books=books)
if __name__ == '__main__':
app.run(debug=True)
实例效果:
补充:测试函数的定义及使用
上面 loop.first 就是一个测试函数,这个我们也可以自定义,自定义测试函数是用template_test()。如定义current_link,此处用于判断link是否是当前url.
@app.template_test('current_link')
def is_current_link(link):
return link == request.path
@app.route('/')
def index():
return render_template('index.html')
@app.route('/services')
def services():
return '这是Services!'
@app.route('/about')
def about():
return '这是About!'
<body>
{% set links = [
('home',url_for('.index')),
('service',url_for('.services')),
('about',url_for('.about')),
] %}
<nav>
{% for label,link in links %}
{% if not loop.first %}|{% endif %}
{# current_link是用来判断当前link是否为当前url #}
<a href="{% if link is current_link %}#
{% else %}
{{ link }}
{% endif %}
">{{ label }}</a>
{% endfor %}
</nav>
</body>
以上笔记来源于知了课堂黄勇老师讲解的教学视频《Flask框架入门到实战开发》的第二章第3-4小结的学习笔记