django自定義過濾器例項

pythontab發表於2013-10-17

需求:透過以鍵方式從字典中取值,如 test[key]=value

views.py

from django.template import RequestContext
from django.shortcuts import render_to_response
def view(request)
    dicts = {"key1": 1, "key2": 2, "key3": 3, } 
    return render_to_response("index.html",  {"dicts":dicts,},context_instance = RequestContext(request))

1.在app目錄下建立templatetags/在此目錄下建立空檔案__init__.py和myfilter.py

2.在myfilter.py編輯

from django import template
register = template.Library()
def key(d,key_name):
        value = 0
        try:
                value = d[key_name]
        except KeyError:
                value = 0
        return value
register.filter('key',key)

3.在模板中使用

{% load myfilter %} #載入自定認標籤
{{dicts|key:"key1"}}



相關文章