Python/Django

[Django] Django custom template tags

S0PH1A 2020. 1. 9. 20:23
반응형

[Django] Django custom template tags


Django에서 제공하는 django templates의 한계를 극복, 개발자가 직접 template를 제작하여 사용할 수 있다.

 

- custom template_tags는 반드시 앱 안의 "templatetags"폴더 안에 생성해야한다.

폴더 구조

- templatetags폴더가 포함된 앱은 반드시 INSTALLED_APPS 에 선언되어 있어야 한다.

- django templates에 custom templates를 추가한 경우 서버를 재시작해야 정상적으로 적용된다.

 

💁‍ filter

  • django templates 에서 |를 이용해서 사용한다.
  • @register.filter
    • name: 필터 이름
    • is_safe
    • needs_autoescape
    • expects_localtime
  • 파라메터는 기본적으로 1개의 값을 가지며, 추가로 1개 더 받을 수 있다.
from django import template

register = template.Library()


@register.filter
def isupper(val):
    return val.isupper()
{% load templatetags파일명 %}

{{ "abcd"|isupper }}

 

💁‍ Simple tags

  • 파라메터를 0개 또는 여러 개 받을 수 있다.
  • @register.simple_tag
    • name: 태그 이름
    • takes_context
import datetime
from django import template

register = template.Library()


@register.simple_tag
def current_date():
    return datetime.now().strftime("%Y %m %d")

@register.simple_tag(name="get_date")
def get_date(date):
    return datetime.now() + datetime.timedelta(days=int(date))
{% load templatetags파일명 %}

{% current_date as now %}
{% get_date "3" as date %}

{% if get_date > now %}
    <span>Yes</span>
{% else %}
    <span>No</span>
{% endif %}

 

💁‍assignment_tag

assignment_tag는 django 1.4에 개발되었으나, django 2.0 부터는 사용이 불가능하다.
assignment_tag는 python 서버쪽에서 반환한 값을 django template에서 as를 이용해서 변수로 만들어 django template에서 사용할 수 있도록 하는 태그였으나, simple_tag도 같은 역할을 할 수 있기에 삭제된 것 같다.

 

더보기

Django 1.4 added the assignment_tag helper to ease the creation of template tags that store results in a template variable.
The simple_tag() helper has gained this same ability, making the assignment_tag obsolete.
Tags that use assignment_tag should be updated to use simple_tag.

- https://docs.djangoproject.com/en/3.0/releases/1.9/#assignment-tag

 

 


[참고] https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/

반응형