Flask中默认的模板语言是Jinja2
STUDENT = { 'name': 'Old', 'age': 38, 'gender': '中'},STUDENT_LIST = [ { 'name': 'pj', 'age': 38, 'gender': '中'}, { 'name': 'lc', 'age': 73, 'gender': '男'}, { 'name': 'fy', 'age': 84, 'gender': '女'}]STUDENT_DICT = { 1: { 'name': 'pj', 'age': 38, 'gender': '中'}, 2: { 'name': 'lc', 'age': 73, 'gender': '男'}, 3: { 'name': 'fy', 'age': 84, 'gender': '女'},}
Jinja2模板中的流程控制:
I. Jinja2模板语言中的 for
{% for foo in g %}{ % endfor %}
II. Jinja2模板语言中的 if
{% if g %}{ % elif g %} { % else %} { % endif %}
1. 使用STUDENT字典传递至前端
后端:
@app.route("/student")def index(): return render_template("student.html", student=STUDENT)
前端:
Old Boy EDU Welcome to Old Boy EDU{ { student }}
{ { student.name }} | { { student["age"] }} | { { student.get("gender") }} |
从这个例子中,可以看出来,字典传入前端Jinja2 模板语言中的取值操作, 与Python中的Dict操作极为相似,并且多了一个student.name的对象操作
2. STUDENT_LIST 列表传入前端Jinja2 模板的操作:
后端:
@app.route("/student_list")def student_list(): return render_template("student_list.html", student=STUDENT_LIST)
前端:
Old Boy EDU Welcome to Old Boy EDU{ { student }}
{ { foo }} | { { foo.name }} | { { foo.get("age") }} | { { foo["gender"] }} |
如果是需要循环遍历的话,Jinja2 给我们的方案是
{% for foo in student %} { { foo }} {% endfor %}
上述代码中的 foo 就是列表中的每一个字典,再使用各种取值方式取出值即可
3.STUDENT_DICT 大字典传入前端 Jinja2 模板
后端:
@app.route("/student_dict")def student_dict(): return render_template("student_dict.html", student=STUDENT_DICT)
前端:
Old Boy EDU Welcome to Old Boy EDU
{ { foo }} | { { student.get(foo).name }} | { { student[foo].get("age") }} | { { student[foo]["gender"] }} |
在遍历字典的时候,foo 其实是相当于拿出了字典中的Key
4.结合所有的字符串儿全部专递前端Jinja2 模板
后端:
@app.route("/allstudent")def all_student(): return render_template("all_student.html", student=STUDENT , student_list = STUDENT_LIST, student_dict= STUDENT_DICT)
前端:
Old Boy EDU _____________________________________Welcome to Old Boy EDU : student{ { student }}
{ { student.name }} | { { student["age"] }} | { { student.get("gender") }} |
_____________________________________
Welcome to Old Boy EDU : student_list { { student_list }}
{ { foo }} | { { foo.name }} | { { foo.get("age") }} | { { foo["gender"] }} |
_____________________________________
Welcome to Old Boy EDU : student_dict { { student_dict }}
{ { foo }} | { { student_dict.get(foo).name }} | { { student_dict[foo].get("age") }} | { { student_dict[foo]["gender"] }} |
render_template中可以传递多个关键字
5.利用 **{}字典的方式传递参数
前端不变(标题4的前端代码)
后端:
@app.route("/allstudent")def all_student(): return render_template("all_student.html", **{ "student":STUDENT , "student_list" : STUDENT_LIST, "student_dict": STUDENT_DICT})