遇到未知标签“加载”。?

我想添加一些自定义模板标签。但是,{% load userfilters %} => 'load' 标签不起作用。


settings.py

# project/settings.py

TEMPLATES = [

    {

        'BACKEND': 'django.template.backends.jinja2.Jinja2',

        'DIRS': [

            os.path.join(BASE_DIR, 'html/jinja2'),

        ],

        'APP_DIRS': True,

        'OPTIONS': {

            'environment': 'accountv1.jinja2.environment',

        },

    },

]

jinja2.py

# project/jinja2.py

from django.templatetags.static import static

from django.urls import reverse


from jinja2 import Environment



def environment(**options):

    env = Environment(**options)

    env.globals.update({

        'static': static,

        'url': reverse,

    })

    return env

应用程序/模板标签/userfilters.py

from django import template


register = template.Library()



@register.filter(name='a')

def a(value):

    return 1

views.py

# use django-rest-framework

class IndexView(generics.GenericAPIView):

    renderer_classes = [TemplateHTMLRenderer]

    template_name = 'index.html'


    def get(self, request, *args, **kwargs):

        return Response({'name': 'max'})

演示.html


不管用

{% load userfilters %}

<!-- custom filter -->

{{ name|a }}

是工作

<!-- default filter -->

{{ name|title }}

我希望能解决这个问题。


宝慕林4294392
浏览 170回答 1
1回答

Helenr

Jinja2中没有load标签,过滤器的工作方式也略有不同(它们只是函数)。templatetags/*.py 是一个 Django 模板约定,而 Jinja2 根本不使用它们。您需要在设置环境的位置注册过滤器:def environment(**options):&nbsp; &nbsp; env = Environment(**options)&nbsp; &nbsp; env.globals.update({&nbsp; &nbsp; &nbsp; &nbsp; 'static': static,&nbsp; &nbsp; &nbsp; &nbsp; 'url': reverse,&nbsp; &nbsp; })&nbsp; &nbsp; env.filters.update({&nbsp; &nbsp; &nbsp; &nbsp; 'a': a,&nbsp; &nbsp; })&nbsp; &nbsp; return env另一种选择是使用django-jinja模板后端而不是 Django 内置的 Jinja2 后端;它更有特色,并且支持templatetags开箱即用的样式加载。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python