Django 模板中的多个加载标签

Raj*_*jay 2 python django django-templates django-filter

目录结构

app_one
    templatetags
        __init__.py
        filter_one.py
app_two
    templates
        app_two
            template_one.py
    templatetags
        __init__.py
        filter_two.py
Run Code Online (Sandbox Code Playgroud)

filter_one.py 中有一些过滤器,filter_two.py 中有一些过滤器。template_one.html 中这些过滤器的每个用法都在起作用。

然后我在 filter_one.py 中又添加了两个过滤器

filter_one.py

@register.filter
def f1(val):
    return val['evaluations'][0]['range']

@register.filter
def f2(val)
    return val['evaluations'][1]['data-type']
Run Code Online (Sandbox Code Playgroud)

模板_one.html

{% load filter_one %}
{% load filter_two %}
{{ value | f1 }}
Run Code Online (Sandbox Code Playgroud)

这会产生错误“无效的过滤器:f1”。

但是当我将模板移动到 filter_two.py 时它会起作用

想不通背后的逻辑!

Наз*_*кий 6

您实际上不需要编写.py,与通常的 python 模块导入相同。只需按如下方式编写代码:

{% load filter_one %}
{% load filter_two %}
Run Code Online (Sandbox Code Playgroud)

如果你想保存一些行,你实际上可以在一行中加载标签,模块名称用空格分隔:

{% load filter_one filter_two %}
Run Code Online (Sandbox Code Playgroud)