自定义django模板的 tags和filters
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
有一个应用polls结构如下,如何自定义templatetags
polls/__init__.pymodels.pytemplatetags/__init__.pypoll_extras.pyviews.py
一,安装polls
INSTALLED_APPS=[.....'polls']
在polls目录下新建一个templatetags目录,目录下创建一个空文件__init__.py以让python识别到其是一个包
1.自定义filterfromdjangoimporttemplateregister=template.Library()@register.filter(name='cut')defcut(value,arg):returnvalue.replace(arg,'')@register.filterdeflower(value):returnvalue.lower()
开启takes_context,可以访问当前上下文context
importdatetimefromdjangoimporttemplateregister=template.Library()@register.simple_tag(takes_context=True)defcurrent_time(context,format_string):#context接收当前页面的上下文字典timezone=context['timezone']returnyour_get_current_time_method(timezone,format_string)
#results.html
<ul>{%forchoiceinchoices%}<li>{{choice}}</li>{%endfor%}</ul>
@register.inclusion_tag('results.html')defshow_results(poll):choices=poll.choice_set.all()return{'choices':choices}
{%show_resultspoll%}//返回如下<ul><li>Firstchoice</li><li>Secondchoice</li><li>Thirdchoice</li></ul>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。