淺談Django自定義模板標簽template_tags的用處
自定義模板標簽,過濾器。英文翻譯是Customtemplatetagsandfilters。customfilter自定義過濾器今天不在我的記錄范圍之內,以后用到再看官方文檔也不遲。
**問題1:**customtemplatetags到底長啥樣?
Manytemplatetagstakeanumberofarguments–stringsortemplatevariables–andreturnaresultafterdoingsomeprocessingbasedsolelyontheinputargumentsandsomeexternalinformation.Forexample,acurrent_timetagmightacceptaformatstringandreturnthetimeasastringformattedaccordingly.
Toeasethecreationofthesetypesoftags,Djangoprovidesahelperfunction,simple_tag.Thisfunction,whichisamethodofdjango.template.Library,takesafunctionthatacceptsanynumberofarguments,wrapsitinarenderfunctionandtheothernecessarybitsmentionedaboveandregistersitwiththetemplatesystem.
(為了降低customtags的難度,你可以使用Django提供的快捷函數(shù)simple_tag)
Ourcurrent_timefunctioncouldthusbewrittenlikethis:
import datetime from django import template register = template.Library()# 只有向系統(tǒng)注冊過的tags,系統(tǒng)才認得你。 @register.simple_tag(takes_context=True)#加上這句后我就是一名合格的template tags def current_time(context, format_string): timezone = context['timezone'] return your_get_current_time_method(timezone, format_string)
Note that the first argument must be called context.
Note that the first argument must be called context.
Note that the first argument must be called context.
@register.simple_tag(takes_context=True)
# 這個裝飾器表明這個函數(shù)是一個模板標簽,takes_context = True 表示接收上下文對象,就是前面所說的封裝了各種變量的 Context 對象。
def paginate(context, object_list ,page_count):
# context是Context 對象,object_list是你要分頁的對象,page_count表示每頁的數(shù)量 , page_count
left = 3 # 當前頁碼左邊顯示幾個頁碼號 -1,比如3就顯示2個
right = 3 # 當前頁碼右邊顯示幾個頁碼號 -1
paginator = Paginator(object_list, page_count) # 通過object_list分頁對象
page = context['request'].GET.get('page') # 從 Http 請求中獲取用戶請求的頁碼號
try:
object_list = paginator.page(page) # 根據(jù)頁碼號獲取第幾頁的數(shù)據(jù)
context['current_page'] = int(page) # 把當前頁封裝進context(上下文)中
pages = get_left(context['current_page'], left, paginator.num_pages) + get_right(context['current_page'], right,
paginator.num_pages)
# 調用了兩個輔助函數(shù),根據(jù)當前頁得到了左右的頁碼號,比如設置成獲取左右兩邊2個頁碼號,那么假如當前頁是5,則 pages = [3,4,5,6,7],當然一些細節(jié)需要處理,比如如果當前頁是2,那么獲取的是pages = [1,2,3,4]
except PageNotAnInteger:
# 異常處理,如果用戶傳遞的page值不是整數(shù),則把第一頁的值返回給他
object_list = paginator.page(1)
context['current_page'] = 1 # 當前頁是1
pages = get_right(context['current_page'], right, paginator.num_pages)
except EmptyPage:
# 如果用戶傳遞的 page 值是一個空值,那么把最后一頁的值返回給他
object_list = paginator.page(paginator.num_pages)
context['current_page'] = paginator.num_pages # 當前頁是最后一頁,num_pages的值是總分頁數(shù)
pages = get_left(context['current_page'], left, paginator.num_pages)
context['article_list'] = object_list # 把獲取到的分頁的數(shù)據(jù)封裝到上下文中
context['pages'] = pages # 把頁碼號列表封裝進去
context['last_page'] = paginator.num_pages # 最后一頁的頁碼號
context['first_page'] = 1 # 第一頁的頁碼號為1
try:
# 獲取 pages 列表第一個值和最后一個值,主要用于在是否該插入省略號的判斷,在模板文件中將會體會到它的用處。注意這里可能產生異常,因為pages可能是一個空列表,比如本身只有一個分頁,那么pages就為空,因為我們永遠不會獲取頁碼為1的頁碼號(至少有1頁,1的頁碼號已經(jīng)固定寫在模板文件中)
context['pages_first'] = pages[0]
context['pages_last'] = pages[-1] + 1
# +1的原因是為了方便判斷,在模板文件中將會體會到其作用。
except IndexError:
context['pages_first'] = 1 # 發(fā)生異常說明只有1頁
context['pages_last'] = 2 # 1 + 1 后的值
return '' # 必須加這個,否則首頁會顯示個None
問題2:自定義完標簽后,在模板中怎么使用呢?

我的自定義過的標簽放在templatetags/paginate_tags.py中

處理函數(shù)
{% load paginate_tags %}#第一步:把文件名包含進來
{% paginate blogposts 2 %} #第二步:調用函數(shù) 添加參數(shù)。注意context參數(shù)不用你傳。
注意:
經(jīng)由defpaginate(context,object_list,page_count):函數(shù)處理過的數(shù)據(jù),在模板中如何使用???
context['article_list'] = object_list # 把獲取到的分頁的數(shù)據(jù)封裝到上下文中 context['pages'] = pages # 把頁碼號列表封裝進去 context['last_page'] = paginator.num_pages # 最后一頁的頁碼號 context['first_page'] = 1 # 第一頁的頁碼號為1
數(shù)據(jù)輸送到函數(shù)中,進行處理,然后將數(shù)據(jù)封裝到之前的context上下文變量中,供template使用,使用方式和使用字典一樣。
總結
以上就是本文關于淺談Django自定義模板標簽template_tags的用處的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站:
如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關文章
Python接口測試數(shù)據(jù)庫封裝實現(xiàn)原理
這篇文章主要介紹了Python接口測試數(shù)據(jù)庫封裝實現(xiàn)原理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-05-05
python 借助numpy保存數(shù)據(jù)為csv格式的實現(xiàn)方法
今天小編就為大家分享一篇python 借助numpy保存數(shù)據(jù)為csv格式的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
python?OpenCV實現(xiàn)圖像特征匹配示例詳解
這篇文章主要為大家介紹了python?OpenCV實現(xiàn)圖像特征匹配示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04

