django框架自定義模板標(biāo)簽(template tag)操作示例
本文實例講述了django框架自定義模板標(biāo)簽(template tag)操作。分享給大家供大家參考,具體如下:
django 提供了豐富的模板標(biāo)簽(template tag)和過濾器(tempalte filter),但這些并非完全能滿足自己的需要,所以django 也提供了自定義模板標(biāo)簽和filter. 自定義這些標(biāo)簽其實很簡單,用一個方法舉例,今天有一個需要在頁面中計算幾個數(shù)的乘積的需求,比如 訂單數(shù)量*訂單價格*商品折扣.
也許有人會說,可以在view中先計算好,然后再顯示在界面上,當(dāng)然,這樣做是可以的。對于比較方便的,確實可以在view中就計算好,如果不方便的,有的數(shù)據(jù)需要組合,拼湊的,也未必方便。所以試著寫如下一個計算乘積的tag:
#coding:utf-8
'''
Created on 2012-12-19
@author: yihaomen.com
計算多個數(shù)的乘積
'''
from django import template
from django.template.base import resolve_variable, Node, TemplateSyntaxError
register = template.Library()
class MulTag(Node):
def __init__(self,numList):
self.numList = numList
def render(self, context):
realList = []
try:
for numobj in self.numList:
realList.append(numobj.resolve(context))
except:
raise TemplateSyntaxError("multag error")
try:
value = realList[0]
for num in realList[1:]:
value = value* num
return round(value,2)
except:
return ''
@register.tag(name="mymul")
def getMulNums(parser, token):
bits = token.contents.split()
realList = [parser.compile_filter(x) for x in bits[1:]]
return MulTag(realList)
基本上所有的django template tag 都是這種寫法,這里需要注意的是
1. 在 getMulNums 方法里的 parser.compile_filter 這個非常重要。
2. 在Multag 中的 numobj.resolve(context)
有了以上的方法,才能正確得到模板中上下文的內(nèi)容,否則你只能寫死內(nèi)容 ({%mymul 3 4 5 6%} 這種方式)
比如,在視圖view的context中有 order ,item,對象 在模板中有如下計算
{% load myMulTag %}
{%mymul order.num item.price item.discount%}
這樣就能計算出值來,無論多少個相乘,都可以得到結(jié)果.
另外還有一點要注意的就是 自己寫的template tag ,一定要保存在app下的 templatetags 目錄下. 否則加載不成功.
這個寫django template tag的方式,具有代表性,其他的tag可以用類似的方法寫出來,寫成自己需要的業(yè)務(wù)規(guī)則就可以,接收的參數(shù)類型不同而已。
參考資料:https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
希望本文所述對大家基于Django框架的Python程序設(shè)計有所幫助。
相關(guān)文章
python 內(nèi)置函數(shù)-range()+zip()+sorted()+map()+reduce()+filte
這篇文章主要介紹了python 內(nèi)置函數(shù)-range()+zip()+sorted()+map()+reduce()+filter(),想具體了解函數(shù)具體用法的小伙伴可以參考一下下面的介紹,希望對你有所幫助2021-12-12
Python中for循環(huán)語句實戰(zhàn)案例
這篇文章主要給大家介紹了關(guān)于Python中for循環(huán)語句的相關(guān)資料,python中for循環(huán)一般用來迭代字符串,列表,元組等,當(dāng)for循環(huán)用于迭代時不需要考慮循環(huán)次數(shù),循環(huán)次數(shù)由后面的對象長度來決定,需要的朋友可以參考下2023-09-09
Keras搭建Mask?R-CNN實例分割平臺實現(xiàn)源碼
這篇文章主要為大家介紹了Keras搭建Mask?R-CNN實例分割平臺實現(xiàn)源碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05
pytorch中permute()函數(shù)用法補充說明(矩陣維度變化過程)
這篇文章主要給大家介紹了關(guān)于pytorch中permute()函數(shù)用法補充說明的相關(guān)資料,本文詳細說明了permute函數(shù)里維度變化的詳細過程,需要的朋友可以參考下2022-04-04
python通過shutil實現(xiàn)快速文件復(fù)制的方法
這篇文章主要介紹了python通過shutil實現(xiàn)快速文件復(fù)制的方法,涉及Python中shutil模塊的使用技巧,需要的朋友可以參考下2015-03-03

