django创建模板过滤器

时间:2012-08-23 01:46:03

标签: django django-template-filters

views.py

@register.filter(name="avl")
def avl_facilities(obj):
    return obj.avl_facilities()

@register.filter
def na_facilities(obj):
    return obj.na_facilities()

models.py

class Model(models.Model):
#some code .....
    def avl_facilities(self):
        item = ['bar','bank','music','wifi','offers','credit']
        avl = []
        for i in item:
            if getattr(self,i) == True:
                avl.append(i)
        return avl
    def na_facilities(self):
        item = ['bar','bank','music','wifi','offers','credit']
        na = []
        for i in item:
            if getattr(self,i) == False:
                na.append(i)
        return na

的HTML

<div class="facility pad10">
    {% for item in data.rest|avl %}
/* data.rest is appropriate instance of model defined above*/
    <span class="label label-danger mrg2 pad5 pull-left">
    {{item|title}}
    </span>
    {% endfor %}
</div>

errro

Invalid filter: 'avl_facilities'

疑问

我无法理解,如果模型中的avl_facilities返回正确的可迭代列表,但它不能作为模板过滤器,请提前感谢

1 个答案:

答案 0 :(得分:3)

您无法在views.py中定义过滤器。您必须将它们放在templatetags目录中的新文件中。

你应该知道,这两个过滤器都是完全没必要的。只要不接受参数,就可以从模板中调用模型方法:

{% for item in data.rest.avl_facilities %}