주 메뉴 열기
대문
임의의 문서로
로그인
설정
Pywiki 소개
면책 조항
Pywiki
검색
바뀜
← 이전 편집
다음 편집 →
3. 장고 탬플릿 필터
(편집)
2022년 6월 9일 (목) 23:41 판
1,220 바이트 추가됨
,
2022년 6월 9일 (목) 23:41
→커스텀 필터 만들기
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>
|}
|}
[[분류:장고 탬플릿]]
[[분류:장고 탬플릿]]
Sam
사무관
,
인터페이스 관리자
,
관리자
, 교사
편집
1,408
번