Django Custom template filter

2011-05-17

django view 到 template 过程中。有时需要 小量的算术运算。 可是,django 默认不支持。呵呵! 只能看文档自己写个了呵呵 步骤如下: 现在自己的 app 添加 templatetags 目录

 tree templatetags/
templatetags/
├── __init__.py
├── app_extras.py

app_extras.py 代码如下:

from django import template

register = template.Library()

#添加 filter 标签
def times(value, arg):
    try:
        return float(value) * float(arg)
    except (ValueError, TypeError):
        return value

def divide(value, arg):
    try:
        return float(value) / float(arg)
    except (ValueError, TypeError):
        return value    

def takeInt(value):
    return int(value)

#注册标签
register.filter(times)
register.filter(divide)
register.filter(takeInt)

如何使用:

{% load app_extras %}
{{ somevariable|add:"1" }}

参考文档:http://docs.djangoproject.com/en/1.2/howto/custom-template-tags/