if语句
格式:
{% if command %}{ % elif %}{ % else %}{ % endif %}
代码示例
flask_one.py
#encoding:utf-8from flask import Flask,url_for,redirect,render_templateapp = Flask(__name__)@app.route('/')def index(is_login): if is_login == "1": #模拟1为登陆成功 user = { "aa":"test", 'bbb':'注销', 'age':"11" } return render_template('index.html',users=user) else: return render_template('index.html')if __name__ == '__main__': app.run(debug=True)
index.html
Title {% if users and users.age >10 %} #这里的users为py文件里传递的user字典,users.age为py文件user字典里的age { { users.aa }} { { users.bbb}} {% else %} 登陆 注册 {% endif %}
url入口:127.0.0.1/{1,0..}
for语句
格式:
{% for .. %}{ % endfor %}
代码实现:
flask_one.py
#encoding:utf-8from flask import Flask,url_for,redirect,render_templateapp = Flask(__name__)@app.route('/')def index(): users = { 'username':'tsdf', 'age':11 } return render_template('index.html',user=users) if __name__ == '__main__': app.run(debug=True)
index.html
Title {% for k,v in user.items() %} #for语句{
{ k }}----{ { v }} {% endfor %}
redirect 传数据到模板语言(flash)
from flask import redirect,flash@app.route('/register',methods=['GET','POST'])def register(): if request.method == 'GET': return render_template('register.html') else: phone = request.form.get('phone') uname = request.form.get('username') pwd = request.form.get('password') pwd1 = request.form.get('password1') user = User.query.filter(User.phone == phone).first() if user is not None: return "用户已经存在" else: if phone == "" or uname == "": flash('手机号或者用户名不能为空') return redirect(url_for('register')) elif pwd != pwd1: flash('两次输入的密码不匹配') return redirect(url_for('register')) else: user = User(phone=phone,username=uname,password=pwd) db.session.add(user) db.session.commit() # user = User.query.filter(User.phone == phone).first() # print (user) return redirect(url_for('login'))
模板语言:
{% extends 'common.html' %}{% block title %} 注册{% endblock %}{% block head %} {% endblock %}{% block body %}{% endblock %}注册
{% for message in get_flashed_messages() %} {
{ message }} {% endfor %}
代码示例:
flask_one.py
#encoding:utf-8from flask import Flask,url_for,redirect,render_templateapp = Flask(__name__)@app.route('/')def index(): books = [ { 'name':'西游记','author':'吴承恩','price':111}, { 'name': '红楼梦', 'author': '曹雪芹', 'price': 121}, { 'name': '水浒传', 'author': '施耐庵', 'price': 131}, { 'name': '三国演义', 'author': '罗贯中', 'price': 141} ] return render_template('index.html',book=books)if __name__ == '__main__': app.run(debug=True)
index.html
Title
书名 | 作者 | 价格 |
---|---|---|
{ { book.name }} | { { book.author }} | { { book.price }} |
自定义错误信息
@app.errorhandler(404)def page_noe_found(error): return render_template('home/404.html'),404@app.errorhandler(500)def page_noe_found(error): return render_template('home/500.html'),500