"3. 장고 탬플릿 필터"의 두 판 사이의 차이

Pywiki
둘러보기로 가기 검색하러 가기
67번째 줄: 67번째 줄:
  
 
<td><a href="...">{{ posting.like_count|sub:posting.dislike_count }} </a></td>
 
<td><a href="...">{{ posting.like_count|sub:posting.dislike_count }} </a></td>
 +
</syntaxhighlight>
 +
|}
 +
 +
=== 커스텀 필터의 고급사용 ===
 +
모든 페이지에 들어가는 view가 필요한데(알림처럼), 그럴 때 view를 일일이 수정해주어야 하기엔 너무 번거롭다. 이럴 땐 탬플릿 필터를 작성하여 base.html에 넣는 편이 좋다.
 +
{| class="wikitable"
 +
!과정
 +
!설명
 +
!방법
 +
|-
 +
|필터 디렉터리 및 파일 만들기
 +
|
 +
* 앱 안에 <code>templatetags</code> 디렉터리를 만든다.
 +
* 이 디렉터리 안에 <code>custom_tags.py</code>를 만든다.(이름은 짓기 나름)
 +
|<syntaxhighlight lang="python">
 +
from django import template
 +
from custom_account.models import Notification
 +
 +
register = template.Library()
 +
@register.inclusion_tag('custom_account/notification.html', takes_context=True)
 +
def show_notifications(context):
 +
    to_user = context['request'].user
 +
    notifications = Notification.objects.filter(to_user=to_user)
 +
    return {'notifications':notifications}
 +
</syntaxhighlight>
 +
|-
 +
|필터 사용
 +
|탬플릿 안에서 필터를 불러온 후 사용한다.
 +
 +
 +
하고 나면 탬플릿 파일이 없다는 에러가 뜰텐데, 적절히 만들어주면 끝.
 +
|<syntaxhighlight lang="html+django">
 +
{% load custom_tags %}
 +
{% show_notifications %}
 
</syntaxhighlight>
 
</syntaxhighlight>
 
|}
 
|}
 
[[분류:장고 탬플릿]]
 
[[분류:장고 탬플릿]]

2022년 6월 9일 (목) 23:41 판

1 개요

탬플릿 내에서 함수처럼 쓰이는 기능이다.(굳이 탬플릿에서 처리할 게 아니라, 연산은 view에서 처리한 후 결과 변수로 넣는 편이 편할 것 같은데..)

그저 데이터형이라든가.. 간단한 조작을 할 땐 유용하다.

특수기능을 사용할 때 외엔 그닥 쓰이지 않는다.

2 탬플릿 필터

파이프문자를 사용하여 함수처럼 작용한다.

{{변수|필터}} 형태로 사용한다.

{{변수|필터|필터2}} 형태로 중복해 사용할 수도 있다.

필터 설명
|add:숫자 숫자만큼 더한다.(음수도 가능)
|safe XSS를 막기 위해 HTML에서 쓰이는 문자들은 자동으로 이스케이프 처리한다.

하지만, HTML태그를 그대로 사용해야 할 때가 있는데, safe필터를 사용하여 해당부분의 제한만 풀거나 {%autoescape%}태그를 사용하여 {%endautoescape%} 사이의 이스케이프를 방지한다.

|default:"문자열" 값이 없거나 False인 경우 대체할 문자열을 지정한다.
|truncatechars:숫자 제목이 길어질 때 특정 숫자의 글자만 나타내고 싶을 때 사용한다.
|timesince 시간 데이터에 붙는다.

게시판에서 작성된지 얼마나 지났는지 보여주기 위해.

더 많은 필터는 https://docs.djangoproject.com/en/3.1/ref/templates/builtins/ 등의 문서를 뒤지자.

각종 필터함수를 만들 수도 있지만 기능에 관련한 것들은 가능하면 view에서 처리하는 편이 디자이너와의 협업에 좋다.

3 커스텀 필터 만들기

놀랍게도 탬플릿 필터 안에 뺄셈이 없다. 하여간, 이런저런 경우 커스텀 필터를 만들어주어야 하는 경우가 생기는데, 빼기 필터를 만들 경우, 다음과 같이 진행한다.

과정 설명 방법
필터 디렉터리 및 파일 만들기
  • 앱 안에 templatetags 디렉터리를 만든다.
  • 이 디렉터리 안에 posting_filter.py를 만든다.(이름은 짓기 나름)
from django import template

register = template.Library()


@register.filter
def sub(value, arg):
    return value - arg
필터 사용 탬플릿 안에서 필터를 불러온 후 사용한다.
{% load posting_filter %}

<td><a href="...">{{ posting.like_count|sub:posting.dislike_count }} </a></td>

3.1 커스텀 필터의 고급사용

모든 페이지에 들어가는 view가 필요한데(알림처럼), 그럴 때 view를 일일이 수정해주어야 하기엔 너무 번거롭다. 이럴 땐 탬플릿 필터를 작성하여 base.html에 넣는 편이 좋다.

과정 설명 방법
필터 디렉터리 및 파일 만들기
  • 앱 안에 templatetags 디렉터리를 만든다.
  • 이 디렉터리 안에 custom_tags.py를 만든다.(이름은 짓기 나름)
from django import template
from custom_account.models import Notification

register = template.Library()
@register.inclusion_tag('custom_account/notification.html', takes_context=True)
def show_notifications(context):
    to_user = context['request'].user
    notifications = Notification.objects.filter(to_user=to_user)
    return {'notifications':notifications}
필터 사용 탬플릿 안에서 필터를 불러온 후 사용한다.


하고 나면 탬플릿 파일이 없다는 에러가 뜰텐데, 적절히 만들어주면 끝.

{% load custom_tags %}
{% show_notifications %}