flask_五、模板相关+模板上下文变量+自定义
一、程序一(简单模板说明)
# encoding=utf-8 from flask import Flask,render_template app = Flask(__name__) @app.route('/watchlist') def watchlist(): return """ <head> <title>xiaxiaoxu's Watchlist</title> </head> <body> <h2>xiaxiaoxu</h2> <i>A man who loves 看电影.</i> <h5>xiaxiaoxu's Watchlist:</h5> <ul> <li>%s</li> </ul> </body> </html>""" % 'My Neighbor Totoro - 1988' app.run()
二、模板示例
#模板的作用:用特殊的额语法来标记变量
2.1 app.py文件
#encoding=utf-8 from flask import Flask,render_template app = Flask(__name__) @app.route('/watchlist') def watchlist(): return render_template('watchlist.html',user=user,movies = movies) @app.route('/hello') def hello(): return '<p>welcome to flask template </p>' user = { 'username': 'xiaxiaoxu', 'bio': 'A man who loves 看电影.' } movies = [ {'name' : 'My Neighbor Totoro','year':'1988'}, {'name': 'Three Colours trilogy', 'year': '1993'}, {'name': 'Forrest Gump', 'year': '1994'}, {'name': 'Perfect Blue', 'year': '1997'}, {'name': 'The Matrix', 'year': '1999'}, {'name': 'Memento', 'year': '2000'}, {'name': 'The Bucket list', 'year': '2007'}, {'name': 'Black Swan', 'year': '2010'}, {'name': 'Gone Girl', 'year': '2014'}, {'name': 'CoCo', 'year': '2017'}] if __name__ == "__main__": app.run(debug = True)
需要在根目录下新建template目录
并在模板目录下新建一个template.html文件
文件内容如下:
2.2 watchlist.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ user.username }}'s Watchlist</title> </head> <body> <a href = "{{ url_for('hello') }}">← Return</a> <h2>{{ user.username }}</h2> {% if user.bio %} <i>{{ user.bio }}</i> {% else %} <i>This user has not provided a bio.</i> {% endif %} {# 下面是电影清单(这是注释) #} <h5>{{ user.username }}'s Watchlist ({{ movies|length }}):</h5> <ul> {% for movie in movies %} <li>loop.index: {{ loop.index }} loop.first: {{ loop.first }} loop.last: {{ loop.last }} - {{ movie.name }} - {{ movie.year }}</li> {% endfor %} </ul> </body> </html>
运行结果:
2.2.1点击return能返回到上层页面
模板渲染过程:把模板中的jinja语法对应的表达式,换成字符串,最后生成一个完整的html文件.
2.4jinja常用的三种定界符
2.4.1、语句
比如if判断、for循环等:
{% … %}
2.4.2、表达式
比如字符串、变量、函数调用等:
{{ … }}
2.4.3、注释
{# … #}
三、渲染模板
渲染模板(渲染模板内容)render_templat
encoding=utf-8 from flask import Flask,render_template,render_template_string app = Flask(__name__) @app.route('/watchlist') def watchlist(): return render_template_string( '''{% for movie in movies %} <li>{{ movie.name }} - {{ movie.year }}</li> {% endfor %}''', movies = movies) #return render_template('watchlist.html',user=user,movies = movies) @app.route('/hello') def hello(): return '<p>welcome to flask template </p>' user = {'username': 'weixingguang', 'bio': 'Two man who loves 看电影.'} movies = [ {'name' : 'My Neighbor Totoro','year':'1988'}, {'name': 'Three Colours trilogy', 'year': '1993'}, {'name': 'Forrest Gump', 'year': '1994'}, {'name': 'Perfect Blue', 'year': '1997'}, {'name': 'The Matrix', 'year': '1999'}, {'name': 'Memento', 'year': '2000'}, {'name': 'The Bucket list', 'year': '2007'}, {'name': 'Black Swan', 'year': '2010'}, {'name': 'Gone Girl', 'year': '2014'}, {'name': 'CoCo', 'year': '2017'}] if __name__ == '__main__': app.run(debug=True)
运行结果:
四、传入jinja2中的变量说明
传入的jinja2中的变量值有哪些?
传入jinja2中的变量值:字符串、类表、字典、函数、类、类实例、列表
4.1 app.py
# encoding=utf-8 from flask import Flask,render_template,render_template_string app = Flask(__name__) @app.route('/watchlist') def watchlist(): return render_template_string('watchlist.html', movies = movies) #return render_template('watchlist.html',user=user,movies = movies) @app.route('/testJinja') def testJinja(): return render_template('testJinja.html', my_list=my_list, my_tuple=my_tuple, my_dict=my_dict, my_func=my_func, my_object=my_object) my_list=[1,2,3,4] my_tuple=('a','b','c','d') my_dict={'d1':'abc','d2':'bcd','d3':'cde'} def my_func(): return "this is my_func~" my_object = "my_object" if __name__ == '__main__': app.run(debug=True)
4.2 模板二testJinja.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>testJinja</title> </head> <body> <p>这是列表my_list的第一个元素:{{ my_list[0] }}</p> <p>这是元祖my_tuple的第一个元素:{{ my_tuple[0] }}</p> <p>这是字典my_dict的键为d1的值:{{ my_dict['d1'] }}</p> <p>这也是字典my_dict的键为d1的值:{{ my_dict.d1 }}</p> <p>这是函数my_func的返回值:{{ my_func() }}</p> <p>这是对象my_object调用某方法的返回值:{{ my_object.upper() }}</p> </body> </html>
4.3 模板watchlist.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ user.username }}'s Watchlist</title> </head> <body> <a href = "{{ url_for('hello') }}">← Return</a> <h2>{{ user.username }}</h2> {% if user.bio %} <i>{{ user.bio }}</i> {% else %} <i>This user has not provided a bio.</i> {% endif %} {# 下面是电影清单(这是注释) #} <h5>{{ user.username }}'s Watchlist ({{ movies|length }}):</h5> <ul> {% for movie in movies %} <li>loop.index: {{ loop.index }} loop.first: {{ loop.first }} loop.last: {{ loop.last }} - {{ movie.name }} - {{ movie.year }}</li> {% endfor %} </ul> </body> </html>
4.4运行结果
五、模板上下文
Flaskrnder_template模板传的变量、
jinjato本身有的变量
模板中自己定义的变量
5.1 app.py文件
# encoding=utf-8 from flask import Flask,render_template,render_template_string app = Flask(__name__) @app.route('/watchlist') def watchlist(): return render_template_string('watchlist.html', movies = movies) #return render_template('watchlist.html',user=user,movies = movies) @app.route('/index/') def index(): return render_template('index.html') @app.route('/testJinja') def testJinja(): return render_template('testJinja.html', my_list=my_list, my_tuple=my_tuple, my_dict=my_dict, my_func=my_func, my_object=my_object) my_list=[1,2,3,4] my_tuple=('a','b','c','d') my_dict={'d1':'abc','d2':'bcd','d3':'cde'} def my_func(): return "this is my_func~" my_object = "my_object" if __name__ == '__main__': app.run(debug=True)
5.2 模板index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> {% set name="gloryroad" %} <p>hello {{ name }}</p> </body> </html>
5.3 运行结果
六、index模板的效果
6.1 app.py
# encoding=utf-8 from flask import Flask,render_template,render_template_string app = Flask(__name__) @app.route('/index/') def index(): return render_template('index.html') @app.route('/watchlist') def watchlist(): return render_template_string('watchlist.html', movies = movies) #return render_template('watchlist.html',user=user,movies = movies) @app.route('/hello') def hello(): return "hello flask" if __name__ == '__main__': app.run(debug=True)
6.2 index.html模板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> {% set name="gloryroad" %} <p>hello {{ name }}</p> {% set navigation %} <li><a href="{{ url_for('watchlist') }}">Watchlist</a></li> <li><a href="{{ url_for('hello') }}">Hello</a></li> {% endset %} {{ navigation }} </body> </html>
6.3 运行结果
七:内置上下文变量
7.1 index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> {% set name="gloryroad" %} <p>hello {{ name }}</p> {% set navigation %} <li><a href="{{ url_for('watchlist') }}">Watchlist</a></li> <li><a href="{{ url_for('hello') }}">Hello</a></li> {% endset %} {{ navigation }} <hr /> <p>config: {{ config }}</p> <p>config.DEBUG: {{ config.DEBUG }}</p> <p>request: {{ request }}</p> <p>request.method: {{ request.method }}</p> <p>session: {{ session }}</p> <p>g: {{ g }}</p> </body> </html>
7.2运行结果
八:自定义上下文变量
8.1.app.py
# encoding=utf-8 from flask import Flask,render_template,render_template_string app = Flask(__name__) @app.route('/index/') def index(): return render_template('index.html') @app.route('/watchlist') def watchlist(): return render_template_string('watchlist.html', movies = movies) #return render_template('watchlist.html',user=user,movies = movies) @app.route('/hello') def hello(): return "hello flask" @app.context_processor # 该装饰器返回的是要是字典才可以用 def inject_foo(): foo = 'I am foo.' return dict(foo=foo)#等同于return {'foo': foo} if __name__ == '__main__': app.run(debug=True)
8.2 模板index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <p>foo: {{ foo }}</p> </body> </html>
8.3运行结果
九、自定义全局函数
9.1自定义全局函数示例
# encoding=utf-8 from flask import Flask,render_template,render_template_string app = Flask(__name__) @app.route('/index/') def index(): return render_template('index.html') @app.route('/watchlist') def watchlist(): return render_template_string('watchlist.html', movies = movies) #return render_template('watchlist.html',user=user,movies = movies) @app.route('/hello') def hello(): return "hello flask" @app.context_processor def inject_foo(): foo = 'I am foo.' return dict(foo=foo)#等同于return {'foo': foo} @app.template_global() def bar(): return 'I am bar.' if __name__ == '__main__':
或者
# encoding=utf-8 from flask import Flask, render_template, render_template_string app = Flask(__name__) @app.route('/watchlist') def watchlist(): return render_template_string('watchlist.html', movies = movies) #return render_template('watchlist.html',user=user,movies = movies) @app.route('/hello') def hello(): return "hello flask" @app.route('/index/') def index(): return render_template('index.html') @app.context_processor def inject_foo(): foo = 'I am foo.' return dict(foo=foo) # 等同于return {'foo': foo} @app.template_global() def bar(): return 'I am bar.' @app.template_global(name='barfunc') def bar(): return 'I am bar.' if __name__ == '__main__': app.run(debug=True)
9.2 模板index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> {% set name="gloryroad" %} <p>hello {{ name }}</p> {% set navigation %} <li><a href="{{ url_for('watchlist') }}">Watchlist</a></li> <li><a href="{{ url_for('hello') }}">Hello</a></li> {% endset %} {{ navigation }} <hr /> <p>config: {{ config }}</p> <p>config.DEBUG: {{ config.DEBUG }}</p> <p>request: {{ request }}</p> <p>request.method: {{ request.method }}</p> <p>session: {{ session }}</p> <p>g: {{ g }}</p> <p>调用bar()的结果: {{ bar() }}</p> <!--或者--> <p>调用barfunc()的结果: {{ barfunc() }}</p> </body> </html>
9.3 运行结果
十:自定义上下文返回字典函数
10.1 app.py
# encoding=utf-8 from flask import Flask,render_template,render_template_string app = Flask(__name__) @app.route('/index') def index(): return render_template('index.html') @app.route('/watchlist') def watchlist(): return render_template_string('watchlist.html', movies = movies) #return render_template('watchlist.html',user=user,movies = movies) @app.route('/hello') def hello(): return "hello flask" @app.template_global(name='barfunc') def bar(): return 'I am bar.' @app.context_processor def inject_foo(): return dict(my_func=my_func) def my_func(): return "this is my_func~" if __name__ == '__main__': app.run(debug=True)
10.2 index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> {% set name="gloryroad" %} <p>hello {{ name }}</p> {% set navigation %} <li><a href="{{ url_for('watchlist') }}">Watchlist</a></li> <li><a href="{{ url_for('hello') }}">Hello</a></li> {% endset %} {{ navigation }} <hr /> <p>config: {{ config }}</p> <p>config.DEBUG: {{ config.DEBUG }}</p> <p>request: {{ request }}</p> <p>request.method: {{ request.method }}</p> <p>session: {{ session }}</p> <p>g: {{ g }}</p> <p>调用bar()的结果: {{ bar() }}</p> <!--或者--> <p>调用barfunc()的结果: {{ barfunc() }}</p> <hr /> <p>my_func(): {{ my_func() }}</p> </body> </html>
10.3运行结果