`
hanyh
  • 浏览: 230007 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

django的template filter另类使用

阅读更多
通常我们使用filter都是对原始数据的直接处理,比如说调整时间格式,字符串截断等。我在一小项目中面临一个要每根据一个目录下面的子项,每3个显示为一行,因为django的template不能写逻辑,于是我用了filter传送id,返回生成的html代码:
生存效果如:
××××××××××××××××××××××××××××大项
====         ====       === 小项


template代码
{% load insititute %}  load the filter
{% for obj in object_list %}
<table id="zone_title_bar">
	<tr><td id='zone_icon'></td><td>{{ obj.name }}</td></tr>
</table>
{{ obj.id|insititute_list|safe }} 根据id返回内容
 
{% endfor %}


filter代码
#coding=utf-8
from django import template
from django.template import Library

from bnu.apps.teacher.models import Entry,Institute

register = Library()

def insititute_list(id):
    "Removes all values of arg from the given string"
    objects = Entry.objects.get(id__exact=int(id)).institute_set.all()
    count = 0
    str ="<table>"
    for obj in objects:
        if(count % 3 == 0):
            str += "<tr>"
        strid= "%s" % obj.id
        str += "<td class='insititute_item'><a href='/insititute/"+strid+"/' target='_blank'>"+obj.name+"</td>"
        count += 1
        if(count %3 == 0):
            str += "</tr>"
    if(count % 3) != 0:
        str += "</tr>"
    str +="</table>"
    return str
#这有一点小问题,如果是4个子项,新一行没有褙够td标记
register.filter('insititute_list', insititute_list)
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics