2008-03-07
django的template filter另类使用
关键字: djagno
通常我们使用filter都是对原始数据的直接处理,比如说调整时间格式,字符串截断等。我在一小项目中面临一个要每根据一个目录下面的子项,每3个显示为一行,因为django的template不能写逻辑,于是我用了filter传送id,返回生成的html代码:
生存效果如:
template代码
filter代码
生存效果如:
××××××××××××××××××××××××××××大项 ==== ==== === 小项
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)
发表评论
提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则
- 浏览: 1364 次
- 性别:

- 来自: 北京

- 详细资料
搜索本博客
最近加入圈子
最新评论
-
根据链接判断用户是否登录 ...
建议 if request.path.startswith("/operate" ...
-- by duka -
根据链接判断用户是否登录 ...
我用的是基于数据库的session,怎么做到关闭浏览器后,session就失效?
-- by hama -
根据链接判断用户是否登录 ...
可以在setting里面设置SESSION_COOKIE_AGE(单位:秒),缺 ...
-- by hellas -
根据链接判断用户是否登录 ...
在Java里的web.xml设置<session-config> ...
-- by andrewleung -
jQuery的DOM操作真是太方 ...
那是你写的树有问题吧。大树展开的时候用ajax,展开后缓存
-- by hanyh






评论排行榜