码迷,mamicode.com
首页 > 其他好文 > 详细

自定义django模板的 tags和filters

时间:2017-01-12 03:17:03      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:tags   django   filters   templates   

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


 一,安装polls

INSTALLED_APPS = [
.....
‘polls‘
]


,新建templatetags

polls目录下新建一个templatetags目录,目录下创建一个空文件__init__.py以让python识别到其是一个包

 

1.自定义filter

 

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

<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>



本文出自 “quxf2012” 博客,请务必保留此出处http://quxf2012.blog.51cto.com/12149748/1891167

自定义django模板的 tags和filters

标签:tags   django   filters   templates   

原文地址:http://quxf2012.blog.51cto.com/12149748/1891167

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!