邏輯與循環
[TOC]
if 語句
語法:
{% if xxx %}
{% else %}
{% endif %}
例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
{% if user and user.age > 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:
user = {
'username' : u'站長',
'age' : 22
}
return render_template('index.html', user= user)
# 已經注冊則傳進去參數
else:
return render_template('index.html')
# 沒有注冊則直接渲染
for循環遍歷
字典遍歷:語法和python一樣,可以使用items()
、keys()
、values()
、iteritems()
、iterkeys()
、itervalues()
{% for k,v in user.items() %}
<p>{{ k }}:{{ v }}</p>
{% endfor %}
# for遍歷字典
@app.route('/')
def index():
# 定義一個字典
user = {
'username' : u'站長',
'age' : 22
}
return render_template('index.html',user=user)
列表遍歷:,語法與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' : 88
},
{
'name': u'三國演義',
'author': u'羅貫中',
'price': 98
},
{
'name': u'紅樓夢',
'author': u'曹雪芹',
'price': 89
},
{
'name': u'水滸傳',
'author': u'施耐庵',
'price': 101
}
]
return render_template('index.html', books=books)
if __name__ == '__main__':
app.run(debug=True)