[230119 - TIL] Django cumstom template tags and filters

Dongwoo Kim·2023년 1월 19일
0

TIL / WIL

목록 보기
72/113

1. 개요

: 장고 템플릿을 이용해 변수를 보여줄 때 커스텀한 필터를 추가하여 내용을 변경시킬 수 있다.


2. 방법

0) 프로젝트 구조

projcet
    ├── project
    │	
    ├── templates   
    │		└── index.html
    └── user
         │
         ├── templatetags
         │		├── __init__.py
         ...    └── filter_func.py

1) templatetags 폴더 생성

: html 랜더링을 수행하는 view app에 생성

2) 필터링을 수행할 함수 작성

: 위 구조에서는 filter_func.py 에 작성

# user/templatetags/filter_func.py

def filter_func_test(word):
	return f"custom filtering test - {word}"

3) 관련 decorator 추가

# user/templatetags/filter_func.py

from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter(name='filter_func_test')
@stringfilter
def filter_func_test(word):
	...

4) html에서 {% load %}후 filter적용

# templates/index.html

{% load filter_func %}

{{ test_word | filter_func_test }}

5) 테스트용 view 작성

# user/views.py

from django.shortcuts import render
from rest_framework.views import APIView

class UserView(APIView):
    def get(self, request):
        test_word = "hello world"
        return render(request, "index.html", {"test_word": test_word})

3. 적용 화면



구현코드

참고

profile
kimphysicsman

0개의 댓글