본문 바로가기

카테고리 없음

Django Template filter tag 만들기 # custom template filter tag

728x90
반응형
 

1. 원하는 곳에 폴더/파일 생성

  ex) 프로젝트 최상단에 templatetags/replaceto.py 생성

 

2. settings.py 의 TEMPLATES에 등록

TEMPLATES = [
    {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [BASE_DIR / 'templates'],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
        'libraries':{
            'customtags': 'templatetags.replaceto',   # 이부분!!  # load 할때 key 값으로 불러온다. 이경우는 ex) {% load customtags %}
        }
        },
    },
]

 

 

3. templatetags/__init__.py 만들어서 templatetags 폴더 안의 파일이 import 되도록 moudule화

 

4. templatetags/replaceto.py

from django import template

register = template.Library()

@register.filter
def replace(value):
    return value.replace("#",'_shop')
 
 

5. template으로 가서 load, filter

{% load customtags %} 	# settings.py에 선언한 key 값으로 load
{{data|replace}}      	# key값에 폴더/파일 안에 선언해준 함수값으로 필터 태그

 

 

* 주의 사항!

  변동사항 있을 시 자동으로 반영 안됨! 반드시 filter tag 관련한 설정을 변경해줬다면 서버를 재시작!

 

* 아래와 같이 return에 and를 넣어서 여러 replace도 가능

@register.filter
def replace_shop(value):
    return value.replace("#",'_shop') and value.replace("++", "_shop")

 

* translate

   바꿔야할 문자들을 한번에 바꿀 수 있는 기능, replace.replace를 하면 문자들이 중복되는 경우 꼬일 수 있는데,       
   translate의 str.maketrans를 쓰면 알맞게 변형 가능
@register.filter
def replace_shop(value):
    return value.translate(str.maketrans({'#':'sharp', '+': 'plus'}))
 
 
  '++':'_shop' 과 같이 하려고 하면
   ValueError: string keys in translate table must be of length 1 발생
 
  아래 사이트에서 보면 긴 문자열을 바꾸는 방법들을 소개한다.

 

 

* 기본 Template filter 

728x90
반응형