요구 사항: 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. 앱 디렉토리에 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"}}
을 사용하세요.