장고 - 커스텀 템플릿 태그 생성

  • 템플릿 문법을 사용하다보면 필요한 기능이 없는 경우가 있다.
  • 이럴 때 직접 커스텀 탬플릿 태그를 만들어 사용할 수 있다.

커스텀 탬플릿 태그 생성 방법

1. templatetags 폴더 생성

  • 앱 > templatetags 폴더

2. 원하는 기능을 작성할 파일 생성 및 코드 작성

  • 앱 > templatetags > blog.py
  • 템플릿 라이브러리 변수 생성
    1
    2
    from django import template
    register = template.Library()

3. 필터 등록할 때는 아래와 같이 코드 작성

  • 앱 > templatetags > blog.py

    1
    2
    3
    @register.filter
    def add_two(value):
    return value + 2
  • 등록한 필터는 아래와 같이 사용

    1
    2
    {% load blog %}
    {{변수|add_two}}

4. 태그 등록 시, 아래와 같이 코드 작성

  • 앱 > templatetags > blog.py

    1
    2
    3
    @register.simple_tag
    def print_template():
    return render_to_string('blog/test.html')
  • 등록한 태그는 아래와 같이 사용

    1
    2
    {% load blog %}
    {% print_template %}
  • 태그 실행 결과를 변수로 지정하려면 as 키워드 사용

    1
    2
    3
    {% load blog %}
    {% print_template as test %}
    {{test}}

5. 추가 인자가 있는 필터는 아래와 같이 코드 작성

  • 앱 > templatetags > blog.py

    1
    2
    3
    @register.filter
    def string_append(left, right):
    return left + "-" + right
  • 해당 필터는 아래와 같이 사용

    1
    2
    {% load blog %}
    {{'string1'|string_append:'string2'}}