Flask内置了jinja2,一个极具扩展性的模板系统。下面的例子展示如何在flask中使用jinja2.
创建一个templates的目录,将下面的代码存为flask1.html:
<html> <head> <title>Flask1 Example</title> </head> <body> Say hello to my little friend: {{thing}}. </body> </html>接着再服务器程序中获取这个模板,写入传人的值thing,然后渲染成HTML。flask1.py:
from flask import Flask,render_template app = Flask(__name__) @app.route('/echo/<thing>') def echo(): return render_template('flask1.html',thing=thing) app.run(port=9999,debug=True)运行flask1.py:
python flask1.py输入URL:http://localhost:9999/echo/qixuan
会看到如下效果:
注意:如果将flask1.py和flask1.html同时放在templates时,会出现如下错误:
另外也可以使用url路径传入参数,把参数当做url的一部分,使用这种方法可以直接扩展url本身:
qixuan@ubuntu:~/qixuan02/templates$ cat flask2.html <html> <head> <title>Flask2 Example</title> </head> <body> Say hello to my little friend: {{thing}}. Alas,it just destroyed {{place}}! </body> </html>
qixuan@ubuntu:~/qixuan02$ cat flask2.py from flask import Flask,render_template app = Flask(__name__) @app.route('/echo/<thing>/<place>') def echo(thing,place): return render_template('flask2.html',thing=thing,place=place) app.run(port=9999,debug=True)同样的方式:
此外,还可以用GET参数来传递参数:
from flask import Flask,render_template,request app = Flask(__name__) @app.route('/echo/') def echo(): thing=request.args.get('thing') place=request.args.get('place') return render_template('flask2.html',thing=thing,place=place) app.run(port=9999,debug=True)这次使用如下的url:
http://localhost:9999/echo?thing=qixuan&place=Nanjing在url中使用get命令时,传入的参数形式为&key1=val1&key2=val2&...
也可以使用字典的**操作符向模板中一次性传入字典的多个值。