在django中注册自定义过滤器

use*_*587 6 python django django-templates django-template-filters

我的过滤器没有注册,也不确定它被绊倒的地方.

在test/templatetags中

__init__.py
test_tags.py
Run Code Online (Sandbox Code Playgroud)

test_tags.py包括

from django import template

register.filter('intcomma', intcomma)

def intcomma(value):
    return value + 1
Run Code Online (Sandbox Code Playgroud)

test/templates包含pdf_test.html,其中包含以下内容

{% load test_tags %} 
<ul>
    <li>{{ value |intcomma |floatformat:"0"</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

浮动格式工作正常,但intcomma没有运气

ale*_*cxe 11

首先,你还没有定义register:

要成为有效的标记库,模块必须包含名为register的模块级变量,该变量是template.Library实例,其中注册了所有标记和过滤器.

另外,我通常用以下函数装饰函数register.filter:

from django import template

register = template.Library()

@register.filter
def intcomma(value):
    return value + 1
Run Code Online (Sandbox Code Playgroud)