1 模板引入子html--include

7 模板引擎 - 母版 - include,導入公共的html a. 用法:{% include "pub.html" %}, pub.html還可以添加 {{ name }} b. 一個頁面可以導入多次,一個html只能有一個母版 c.樣例 # public.html <div class="public"> <div class="content"> {{ userinfo }} </div> </div> # app02_test.html <h3>include</h3> {% include "public.html" %} {% include "public.html" %} # views def test(request): return render(request, 'app02_test.html', {'userinfo':{'k1':'v1', 'k2': 'v2'}})
2 模板使用(渲染數據 + 調用函數)

- 模板 - 接收被渲染數據 views參數傳遞:{'userInfo': {'k1': 'v1', 'k2':'v2'}} 前端接收可以 {% for v in userInfo.values %} {% endfor %} 或者 {% for k,v in userInfo.items %} {% endfor %} 或者 {% for k in userInfo.keys %} {% endfor %} - 模板執行函數, 而且函數不是js函數,而是py里面的函數 a.{{ name|upper}} // name是后台傳遞給前端的帶渲染數據,upper是轉換大寫函數
3 自定義函數,供模板調用

- 自定義模板filter a.在應用創建文件夾templatetags b.創建任意py文件, xx.py from django import template register = template.Library() @register.filter def my_upper(value): return value.upper() c.在模板文件導入xx.py 開頭導入 {% load xx %} d.在模板使用函數 {{ 'liuzhipeng'|my_upper}} ,前面的liuzhipeng為參數傳遞給my_upper e. 一定要注冊app_02 - 自定義tag a.在應用創建文件夾templatetags b.創建任意py文件, xx.py from django import template register = template.Library() @register.simple_tag def my_concat(arg1, arg2): return arg1 + arg2 c.在模板文件導入xx.py 開頭導入 {% load xx %} d.在模板使用函數tag {% my_concat "alex" "is sb" %} e. 一定要注冊app_02 - filter 和simple_tag區別 a. filter最多能有兩個參數 b. filter模板調用方式: {{ 參數|函數}} c. simple_tag參數個數無限制 d. simple_tag使用方式:{% 函數 參數 參數 %} e. {% if name|my_bool %} 可以這樣使用filter,而tag則不能 f. simple_tag反向生成url {% url 'url別名' %} g. 可以{% if name|my_bool %}, 但是simple_tag不行