https://docs.djangoproject.com/en/dev/howto/custom-template-tags/html
有一個應用polls結構以下,如何自定義templatetagspython
polls/ __init__.py models.py templatetags/ __init__.py poll_extras.py views.py
一,安裝pollsdjango
INSTALLED_APPS = [ ..... 'polls' ]
在polls目錄下新建一個templatetags目錄,目錄下建立一個空文件__init__.py以讓python識別到其是一個包bash
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()
開啓takes_context,能夠訪問當前上下文contextide
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)
#results.htmlspa
<ul> {% for choice in choices %} <li> {{ choice }} </li> {% endfor %} </ul>
@register.inclusion_tag('results.html') def show_results(poll): choices = poll.choice_set.all() return {'choices': choices}
{% show_results poll %} //返回以下 <ul> <li>First choice</li> <li>Second choice</li> <li>Third choice</li> </ul>