jinja2語法
基本語法
在jinja2中,存在三種語法:
- 控制結構 {% %}
- 變量取值 {{ }}
- 注釋 {# #}
下面是一個簡單的jinja2例子
{# This is jinja code {% for file in filenames %} ... {% endfor %} #}
可以看到,for循環的使用方式和Python比較類似,但是沒有了句尾的冒號,另外需要使用endfor最為結尾,其實在jinja2中,if也是一樣的,結尾需要使用endif。
jinja2變量
jinja2模板中使用 {{ }} 語法表示一個變量,它是一種特殊的占位符。當利用jinja2進行渲染的時候,它會把這些特殊的占位符進行填充/替換,jinja2支持python中所有的Python數據類型比如列表、字段、對象等。
<p>this is a dicectory:{{ mydict['key'] }} </p> <p>this is a list:{{ mylist[3] }} </p> <p>this is a object:{{ myobject.something() }} </p>
jinja2中的過濾器
變量可以通過“過濾器”進行修改,過濾器可以理解為是jinja2里面的內置函數和字符串處理函數。
常用的過濾器有:
過濾器名稱 | 說明 |
safe | 渲染時值不轉義 |
capitialize | 把值的首字母轉換成大寫,其他子母轉換為小寫 |
lower | 把值轉換成小寫形式 |
upper | 把值轉換成大寫形式 |
title | 把值中每個單詞的首字母都轉換成大寫 |
trim | 把值的首尾空格去掉 |
striptags | 渲染之前把值中所有的HTML標簽都刪掉 |
join | 拼接多個值為字符串 |
replace | 替換字符串的值 |
round | 默認對數字進行四舍五入,也可以用參數進行控制 |
int | 把值轉換成整型 |
那么如何使用這些過濾器呢? 只需要在變量后面使用管道(|)分割,多個過濾器可以鏈式調用,前一個過濾器的輸出會作為后一個過濾器的輸入。
{{ 'abc' | captialize }} # Abc {{ 'abc' | upper }} # ABC
{{ 'hello world' | title }} # Hello World {{ "hello world" | replace('world','daxin') | upper }} # HELLO DAXIN {{ 18.18 | round | int }} # 18
jinja2的控制結構
jinja2中的if語句類似與Python的if語句,它也具有單分支,多分支等多種結構,不同的是,條件語句不需要使用冒號結尾,而結束控制語句,需要使用endif關鍵字。
{% if daxin.safe %} daxin is safe. {% elif daxin.dead %} daxin is dead {% else %} daxin is okay {% endif %}
jinja2的for循環
jinja2中的for循環用於迭代Python的數據類型,包括列表,元組和字典。在jinja2中不存在while循環。
迭代列表
<ul> {% for user in users %} <li>{{ user.username|title }}</li> {% endfor %} </ul>
迭代字典
<dl> {% for key, value in my_dict.iteritems() %} <dt>{{ key }}</dt> <dd>{{ value}}</dd> {% endfor %} </dl>
當然也可以加入else語句,在循環正確執行完畢后,執行
在for循環中,jinja2還提供了一些特殊的變量,用以來獲取當前的遍歷狀態:
變量 | 描述 |
loop.index | 當前迭代的索引(從1開始) |
loop.index0 | 當前迭代的索引(從0開始) |
loop.first | 是否是第一次迭代,返回bool |
loop.last | 是否是最后一次迭代,返回bool |
loop.length | 序列中的項目數量 |
loop.revindex | 到循環結束的次數(從1開始) |
loop.revindex0 | 到循環結束的次數(從0開始) |
jinja2的宏
宏類似於Python中的函數,我們在宏中定義行為,還可以進行傳遞參數,就像Python中的函數一樣一樣兒的。
在宏中定義一個宏的關鍵字是macro,后面跟其 宏的名稱和參數等
{% macro input(name,age=18) %} # 參數age的默認值為18 <input type='text' name="{{ name }}" value="{{ age }}" > {% endmacro %}
調用方法也和Python的類似
<p>{{ input('daxin') }} </p> <p>{{ input('daxin',age=20) }} </p>
jinja2的繼承和Super函數
jinja2中最強大的部分就是模板繼承。模板繼承允許我們創建一個基本(骨架)文件,其他文件從該骨架文件繼承,然后針對自己需要的地方進行修改。
jinja2的骨架文件中,利用block關鍵字表示其包涵的內容可以進行修改。
以下面的骨架文件base.html為例:
<!DOCTYPE html> <html lang="en"> <head> {% block head %} <link rel="stylesheet" href="style.css"/> <title>{% block title %}{% endblock %} - My Webpage</title> {% endblock %} </head> <body> <div id="content">{% block content %}{% endblock %}</div> <div id="footer"> {% block footer %} <script>This is javascript code </script> {% endblock %} </div> </body> </html>
這里定義了四處 block,即:head,title,content,footer。那怎么進行繼承和變量替換呢?注意看下面的文件
{% extend "base.html" %} # 繼承base.html文件 {% block title %} Dachenzi {% endblock %} # 定制title部分的內容 {% block head %} {{ super() }} # 用於獲取原有的信息 <style type='text/css'> .important { color: #FFFFFF } </style> {% endblock %} # 其他不修改的原封不同的繼承
PS: super()函數 表示獲取block塊中定義的原來的內容。
模板填充示例
一、准備模板template.html:
<html> <head> <meta charset="UTF-8"> </head> <body> <p style='font-size:15px; font-family:Arial;'>{{ content }}</p> <table border="1" cellspacing="0" cellpadding="0"> <tr> {% if array_table_head %} {% for var_i in array_table_head %} <th style="font-size: 15px; padding: 3px;">{{var_i}}</th> {% endfor %} {% endif %} </tr> {% if dict_table_data %} {% for table_data in dict_table_data %} <tr> <th style="font-size: 12px; padding: 3px;">{{ table_data.Name }}</th> <th style="font-size: 12px; padding: 3px;">{{ table_data.Type }}</th> <th style="font-size: 12px; padding: 3px;">{{ table_data.Value }}</th> </tr> {% endfor %} {% endif %} </table> </body> </html>
二、加載模板
有了上述的html模板,后台利用如下代碼讀入。
import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader('./')) temp = env.get_template('template.html')
注意一點: 其中path需要為當前python文件所在目錄的完整路徑,get_template內部的參數為html模板相對於該python文件所在目錄的路徑(相對路徑)。
三、模擬數據,對模板進行Render
通過第一部分的html模板中我們不難發現該模板一共需要三個變量,content、 array_table_head 以及 dict_table_data。所以我們需要在后台對這三個變量進行模擬。
1. 類型分析。需要注意的是,變量的類型一定要把控好,從模板的觀察可以看出content是直接用{{ }}包裹來引用的,所以在后台應該是一種可以直接取值的類型,例如str, int等。而array_table_head是通過遍歷來引用的,說明最外層在后台是一個List或tuple等可遍歷對象,其次在內層是直接取值的,所以后台應該是一個簡單的str或者int的列表。同理,對於dict_table_data, 則是一個字典字符串,所以三個變量的模擬應該如下:
render_dict = {} dict_table_data = [{'Name': 'Basketball', 'Type': 'Sports', 'Value': 5}, {'Name': 'Football', 'Type': 'Sports', 'Value': 4.5}, {'Name': 'Pencil', 'Type': 'Learning', 'Value': 5}, {'Name': 'Hat', 'Type': 'Wearing', 'Value': 2}] render_dict.update({'Content': 'Hello reader, here is a table:', 'array_table_head': ['Name', 'Type', 'Value'], 'dict_table_data': dict_table_data})
2. 模板渲染
最后一步,即通過render方法將變量放入模板中,然后生成新的html寫入文件,此時,模板語言將會全部被轉化為html。
temp_out = temp.render(content=render_dict['Content'], array_table_head=render_dict['array_table_head'], dict_table_data=render_dict['dict_table_data']) with open(os.path.join('./', 'out.html'), 'w', encoding='utf-8') as f: f.writelines(temp_out) f.close()
完整實例:
import jinja2 import os env = jinja2.Environment(loader=jinja2.FileSystemLoader('./')) temp = env.get_template('template.html') render_dict = {} dict_table_data = [{'Name': 'Basketball', 'Type': 'Sports', 'Value': 5}, {'Name': 'Football', 'Type': 'Sports', 'Value': 4.5}, {'Name': 'Pencil', 'Type': 'Learning', 'Value': 5}, {'Name': 'Hat', 'Type': 'Wearing', 'Value': 2}] render_dict.update({'Content': 'Hello reader, here is a table:', 'array_table_head': ['Name', 'Type', 'Value'], 'dict_table_data': dict_table_data}) temp_out = temp.render(content=render_dict['Content'], array_table_head=render_dict['array_table_head'], dict_table_data=render_dict['dict_table_data']) with open(os.path.join('./', 'out.html'), 'w', encoding='utf-8') as f: f.writelines(temp_out) f.close()
另外一種方式:

from jinja2 import Template TPL = ''' <html> <head> <meta charset="UTF-8"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> </head> <body> <div class="alert alert-primary" role="alert"> A simple primary alert with <a href="#" class="alert-link">an example link</a>. Give it a click if you like. </div> <p style='font-size:15px; font-family:Arial;'>{{ content }}</p> <table border="1" cellspacing="0" cellpadding="0"> <tr> {% if array_table_head %} {% for var_i in array_table_head %} <th style="font-size: 15px; padding: 3px;">{{var_i}}</th> {% endfor %} {% endif %} </tr> {% if dict_table_data %} {% for table_data in dict_table_data %} <tr> <th style="font-size: 12px; padding: 3px;">{{ table_data.Name }}</th> <th style="font-size: 12px; padding: 3px;">{{ table_data.Type }}</th> <th style="font-size: 12px; padding: 3px;">{{ table_data.Value }}</th> </tr> {% endfor %} {% endif %} </table> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> </body> </html> ''' render_dict = {} dict_table_data = [{'Name': 'Basketball', 'Type': 'Sports', 'Value': 5}, {'Name': 'Football', 'Type': 'Sports', 'Value': 4.5}, {'Name': 'Pencil', 'Type': 'Learning', 'Value': 5}, {'Name': 'Hat', 'Type': 'Wearing', 'Value': 2}] render_dict.update({'Content': 'Hello reader, here is a table:', 'array_table_head': ['Name', 'Type', 'Value'], 'dict_table_data': dict_table_data}) content = Template(TPL).render(render_dict) with open('out.html', "w") as f: f.write(content) # 寫入文件
from jinja2 import Template TPL = ''' <html> <head> <meta charset="UTF-8"> </head> <body> <p style='font-size:15px; font-family:Arial;'>{{ content }}</p> <table border="1" cellspacing="0" cellpadding="0"> <tr> {% if array_table_head %} {% for var_i in array_table_head %} <th style="font-size: 15px; padding: 3px;">{{var_i}}</th> {% endfor %} {% endif %} </tr> {% if dict_table_data %} {% for table_data in dict_table_data %} <tr> <th style="font-size: 12px; padding: 3px;">{{ table_data.Name }}</th> <th style="font-size: 12px; padding: 3px;">{{ table_data.Type }}</th> <th style="font-size: 12px; padding: 3px;">{{ table_data.Value }}</th> </tr> {% endfor %} {% endif %} </table> </body> </html> ''' render_dict = {} dict_table_data = [{'Name': 'Basketball', 'Type': 'Sports', 'Value': 5}, {'Name': 'Football', 'Type': 'Sports', 'Value': 4.5}, {'Name': 'Pencil', 'Type': 'Learning', 'Value': 5}, {'Name': 'Hat', 'Type': 'Wearing', 'Value': 2}] render_dict.update({'Content': 'Hello reader, here is a table:', 'array_table_head': ['Name', 'Type', 'Value'], 'dict_table_data': dict_table_data}) content = Template(TPL).render(render_dict) with open('out.html', "w") as f: f.write(content) # 寫入文件