一、模板的基本使用
1、设置模板文件路径:template_folder=‘路径‘
from flask import Flask,render_template # template_folder=‘D:\\templates‘ => 可指定模板路径 默认值为:templates app = Flask(__name__,template_folder=‘templates‘)
1.1:最简单的模板语法
# <p>我是<h1>{{ a }}</h1>参数参数参数参数参数参数</p> @app.route(‘/‘) def home(): a = "后台传过来的" return render_template(‘index.html‘,a=a)
1.2:可以使用**对模板语法进行批量的方式传到前端
""" <body> <div> <p>{{ name }}</p> <p>{{ age }}</p> <p>{{ sex }}</p> </div> ==================== <div> {{ dicts.aa }} {{ dicts[‘aa‘] }} </div> </body> """ @app.route(‘/list/‘) def list(): context = { ‘name‘:‘lee‘, ‘age‘:18, ‘sex‘:‘男‘, ‘dicts‘:{ ‘aa‘:‘aa‘, ‘bb‘:‘bb‘ }, } return render_template(‘posts/list.html‘,**context)
2、对 url_for() 的使用:
语法:{{url_for(‘视图函数名或别名‘,arg1=arg1,arg2=arg2,arg3=arg3)}}
注:如果链接中有参数arg则会补位到链接中不会以GET方式携带
# <p><a href="{{ url_for(‘login‘,next=‘/‘,ref = 77908,uid=15) }}">登陆</a></p> # =>>> http://127.0.0.1:5000/login/15/?next=%2F&ref=77908 @app.route(‘/‘) def index(): return render_template(‘index.html‘) @app.route(‘/login/<uid>/‘) def login(uid): print(uid) return render_template(‘login.html‘)
原文:https://www.cnblogs.com/lee-xingxing/p/12325328.html