python – 在django中注册自定义过滤器

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

在test / templatetags中

__init__.py
test_tags.py

test_tags.py包括

from django import template

register.filter('intcomma', intcomma)

def intcomma(value):
    return value + 1

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

{% load test_tags %} 
<ul>
    <li>{{ value |intcomma |floatformat:"0"</li>
</ul>

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

最佳答案 首先,你
haven’t defined register

To be a valid tag library, the module must contain a module-level
variable named register that is a template.Library instance, in which
all the tags and filters are registered.

另外,我通常用register.filter装饰这个功能:

from django import template

register = template.Library()

@register.filter
def intcomma(value):
    return value + 1
点赞