【问题标题】:could not use custom templatetags in Django 2.0无法在 Django 2.0 中使用自定义模板标签
【发布时间】:2018-06-07 10:14:02
【问题描述】:

我正在使用Django 2.0

我写了几个自定义模板标签在模板里面使用 notes/templatetags/note_tags.py 文件,其中notes 是应用程序目录

我在这个文件中写了几个自定义标签

from django import template
from django.template.defaultfilters import stringfilter
from notepad.utils import simplify_text
from notes.models import Note, ColorLabels

register = template.Library()


@register.filter(name='note_simplify')
@stringfilter
def note_simplify(value):
    return simplify_text(value)


@register.filter(name='default_color_label')
def default_color_label():
    default_label = ColorLabels.objects.filter(default=True).first()
    print(default_label.value)
    return default_label

template 文件中,我已将标签加载为

{% load note_tags %}

我可以使用第一个标签note_simplify,但第二个标签default_color_label 没有被调用。我在同一个文件中使用这两个标签。一个用于修改传递的数据,另一个用于简单地打印一些东西

# modify the note.content
<p>{{ note.content|truncatechars:200|note_simplify }}</p>

# to print some value
{{ default_color_label.value }}

我也多次重启服务器。

有什么问题吗?为什么模板中没有调用标签?

【问题讨论】:

    标签: django django-template-filters django-2.0


    【解决方案1】:

    如果你想要模板中的对象,你需要simple_tag

    @register.simple_tag  
    def default_color_label():
        default_label = ColorLabels.objects.filter(default=True).first()
        return default_label
    

    在 HTML 中你可以使用它。

    {% default_color_label as variable %}
    {{ variable.value }}
    

    注意:您定义了filter 不是标签,而且您使用不正确。 模板过滤器始终与管道运算符一起使用。 {{ somevalue|default_color_label }}

    更新

    assignment_tag 自 1.9 版起已弃用 simple_tag 现在可以将结果存储在 模板变量,应改为使用。

    【讨论】:

    • 它给'Library' object has no attribute 'assignment_tag'错误
    • assignment_tag 装饰器在 1.9 中被弃用,在 2.0 中被移除。请改用simple_tag - 一切都一样。
    猜你喜欢
    • 2015-01-20
    • 2021-09-05
    • 2020-09-25
    • 1970-01-01
    • 2021-07-13
    • 2019-11-16
    • 2012-03-15
    • 2017-09-19
    相关资源
    最近更新 更多