본문으로 바로가기

django 템플릿 필터 사용

category Python 2020. 4. 14. 17:27

해당 APP 디렉토리안에 templatetags 디렉토리 생성

 

그 안에 filters.py 파일생성 (이름은 아무거나..)

 

해당 템플릿에서 {% load filters %} 사용해서 include 

 

{{ 값1|함수명:값2 }} 형식으로 사용

 

 

예) 측정단어 포함시 빨간색으로 표시 (검색에 사용)

 

filters.py

from django import template
register = template.Library()

# REPLACE
@register.filter(name='rep') #filter 이름을 정할 수 있음, 기본으로는 함수 명을 사용 
def replace_val(value, arg):
    low_arg = arg.lower()
    low_value = value.lower()

    if low_arg and low_arg in low_value:
        # 일단 소문자로 비교
        rtntxt = value.replace(arg.lower(), "<font color='#FF1744'>{0}</font>".format(arg.lower()))
        # 대문자로 한번 더 비교
        rtntxt = rtntxt.replace(arg.upper(), "<font color='#FF1744'>{0}</font>".format(arg.upper()))
        return rtntxt
    else:
        return value

 

test.html

{% autoescape off %} //html을 사용하기 위한 설정 
	{{ "문장"|rep:"검색어" }}
{% endautoescape %}

 

 

참조

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags

 

Custom template tags and filters | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

https://himanmengit.github.io/django/2018/02/23/Built-In-Template-Filter.html

 

Django 내장 템플릿 필터 · 초보 웹 프로그래머

 

himanmengit.github.io

 

'Python' 카테고리의 다른 글

Django Rest Api 참고  (0) 2020.03.25
python 코드 안에 한글이 있을경우 오류 발생시  (0) 2020.02.25
python if문 한 줄로 표현  (0) 2020.02.25
python 에러 체크 예제  (0) 2020.02.24
python 문자열에서 html 태그 없애기  (0) 2020.02.24