사용자 정의django 템플릿의tags와 Filters

Custom template tags and filters
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
 
polls 구조는 다음과 같다.templatetags를 어떻게 사용자 정의할 것인가
polls/
    __init__.py
    models.py
    templatetags/
        __init__.py
        poll_extras.py
    views.py

1,polls 설치
INSTALLED_APPS = [
.....
'polls'
]

새 templatetags
polls 디렉터리에 templatetags 디렉터리를 새로 만들고 디렉터리에 빈 파일을 생성합니다init__.py는python이 가방임을 식별하도록 합니다
 
1. 맞춤형 필터
 
from django import templateregister = template.Library()
@register.filter(name='cut')
def cut(value, arg):
    return value.replace(arg, '')
@register.filter
def lower(value):
    return value.lower()

 
2.tag
takes 열기context, 현재 상하문에 접근할 수 있습니다 context
 
import datetime
from django import template
register = template.Library()
 
@register.simple_tag(takes_context=True)
def current_time(context, format_string):#context            
    timezone = context['timezone']
    return your_get_current_time_method(timezone, format_string)

3.Inclusion tags
렌더링된 템플릿을 페이지로 직접 가져오기
#results.html
    {% for choice in choices %}     
  •  {{ choice }} 
  • {% endfor %}


 

@register.inclusion_tag('results.html')
def show_results(poll):
    choices = poll.choice_set.all()
return {'choices': choices}
{% show_results poll %}  //    
  
  • First choice
  •   
  • Second choice
  •   
  • Third choice
  • 좋은 웹페이지 즐겨찾기