파이문

[django] 템플릿에서 Custom tag / filter 사용하기 본문

Python/django

[django] 템플릿에서 Custom tag / filter 사용하기

민Z 2018. 3. 5. 21:25

[django] 템플릿에서 Custom tag / filter 사용하기



django에서 딕셔너리와 조회할 키가 주어졌을 때, 해당 키로 딕셔너리에 접근하고 싶었는데 jinja2 레퍼런스를 비롯해서 django 레퍼런스에도 해당하는 내용이 없었다.


그래서 찾아본 것이 Custom template tags and filters 이다.

django 에서는 템플릿에서 custom filter, tag를 사용할 수 있게 제공하는데, 완전 센세이션.


우선 (꼭! 오타 조심!) templatetags 라는 디렉터리를 생성한다. 이 때, 디렉터리 안에는 무조건 __init__.py 가 있어야 한다. (구조는 아래 처럼 되어 있어야 한다!)

polls/
    __init__.py
    models.py
    templatetags/
        __init__.py
        poll_extras.py
    views.py

polls를 startapp command로 시작한 app_name으로 보면 된다.


그런 다음 html 에서 아래와 같이 최 상단에 작성해준다.

{% load poll_extras %}

나는 모르고 single quote를 넣어서 삽질 했는데, 나와 같은 실수를 하질 않길 바란다! 그냥 파일 이름 그대로 쓰면 된다!


그렇다면 poll_extras.py에는 어떤 내용이 담겨야 하는가?

서두에 적었던 것 처럼 키로 딕셔너리를 접근하고 싶은 태그를 만들고 싶다고 하면 아래와 같이 쓰면 된다.

from django import template

register = template.Library()

@register.simple_tag
def getvalue(d, k):
    return d.get(k) 

그리고 템플릿에서는

{% getvalue test_dictionary test_key %}

이렇게 써주면 된다.


하다 보니까 tag랑 filter가 헷갈리는데, 갓스택오버플로우에 역시나 관련 질답이 있었다.

https://stackoverflow.com/questions/5586774/django-template-filters-tags-simple-tags-and-inclusion-tags


django 공식 레퍼런스에서 더 다양한 예제와 확실한 설명이 있으니 참고하면 좋을 것 같다.

https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/


'Python > django' 카테고리의 다른 글

[django] django에서 데이터베이스 여러개 사용하기  (0) 2018.03.18
Comments