frameworks/django
django template에서 customizing 필터를 사용하는 법
iliosncelini
2019. 9. 4. 16:41
해당 어플리케이션 직하에/ templatetags 디렉토리 생성
예를 들어 example어플리케이션이 타겟이라면, application 디렉토리 아래에 templatetags디렉토리를 생성
example/
__init__.py
models.py
templatetags/
__init__.py
views.pytemplate filter 스크립트 작성
위에서 생성한 templatetags 아래에 스크립트를 생성 후 저장
파일명은 무엇이든 상관 없으나, 이후 template에서 load할 때,파일명으로 불러오게 되므로 주의
(app_root)/templatetags/dict_filter.py
from django.template.defaulttags import register
...
@register.filter
def get_dict(dictionary, key):
return dictionary.get(key)
customizing tag를 호출하기
커스터마이징 태그를 호출하기 위해서는 templatetags 아래있는 작성한 스크립트 명을 호출해야한다 : {% load dict_filter %}
이를 사용할 때는 함수명을 호출하여 사용한다 : {{ mydict|get_dict:item.NAME }}
test.html
{% load dict_filter %}
...
{{ mydict|get_dict:item.NAME }}
...