转:flask之jinja2模板查找路径及关键字传参
转自:https://www.cnblogs.com/qingbaobei7370/p/11330809.html
一、Flask渲染Jinja
模板
- jinja2模板介绍和查找路径
要渲染一个模板,通过render_template
方法即可
①默认路径
from flask import Flask,render_template #指定templates路径 app = Flask(__name__) @app.route('/') def index(): return render_template('index.html')if __name__ == '__main__': app.run(host='127.0.0.1',port=5000,debug=True)
②指定路径
如果想更改模板文件地址,应该在创建app
的时候,给Flask
传递一个关键字参数template_folder
,指定具体的路径
from flask import Flask,render_template #指定templates路径 app = Flask(__name__,template_folder=r'D:\untitled\flask_env\templates') @app.route('/') #@app.route,是一个装饰器 #@app.route('/')就是将url中的/映射到hello_world这个视图函数上面 def index(): return render_template('index.html') @app.route('/huashu/') def huashu(): return render_template('posts/huashu.html') if __name__ == '__main__': app.run(host='127.0.0.1',port=5000,debug=True)
- jinja2模板传参及其技巧
①单个关键字传参,代码如下:
--python--
from flask import Flask,render_template #指定templates路径 app = Flask(__name__,template_folder=r'D:\untitled\flask_env\templates') #传递单个参数 @app.route('/lvzhi/') def lvzhi(): return render_template('posts/lvzhi.html',name='绿植') if __name__ == '__main__': app.run(host='127.0.0.1',port=5000,debug=True)
--HTML--
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>网红绿植</title> </head> <body> <h1>网红绿植</h1> 花样介绍 <p>{{name}}</p> </body> </html>
②多个关键字传参,代码如下:
--python--
from flask import Flask,render_template #指定templates路径 app = Flask(__name__,template_folder=r'D:\untitled\flask_env\templates') @app.route('/') #@app.route,是一个装饰器 #@app.route('/')就是将url中的/映射到hello_world这个视图函数上面 def index(): return render_template('index.html') @app.route('/huashu/') #传递多个参数 def huashu(): context={ 'name':'鲜花', 'price':'¥215', 'describe':{ 'variety1':'玫瑰', 'variety2': '百合' } } return render_template('posts/huashu.html',**context) #传递单个参数 @app.route('/lvzhi/') def lvzhi(): return render_template('posts/lvzhi.html',name='绿植') if __name__ == '__main__': app.run(host='127.0.0.1',port=5000,debug=True)
--HTML--
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>鲜花超市</title> </head> <body> <h1>鲜花超市</h1> 花样介绍 <p>{{name}}</p> <p>{{price}}</p> <p>{{describe.variety1}}</p> <p>{{describe['variety2']}}</p> </body> </html>