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
一,安装polls
INSTALLED_APPS = [ ..... 'polls' ]
在polls目录下新建一个templatetags目录,目录下创建一个空文件__init__.py以让python识别到其是一个包
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,可以访问当前上下文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)
#results.html
<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>
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
文章名称:自定义django模板的tags和filters-创新互联
本文网址:https://www.cdcxhl.com/article16/dhpgdg.html
成都网站建设公司_创新互联,为您提供网站建设、做网站、网站排名、外贸网站建设、标签优化、定制网站
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联