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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值