【问题标题】:How to Use Custom Template Tag in Combination With Django's Built-in "with" Tag?如何结合 Django 内置的“with”标签使用自定义模板标签?
【发布时间】:2021-12-05 19:40:57
【问题描述】:

我有这个简单的标签:

myapp/templatetags/my_filters.py

@register.simple_tag
def get_bookmark_object(content_type, object_id):
    return Bookmark.objects.get(content_type=content_type, object_id=object_id)

在我的模板中,我希望能够做到这一点:

{% load my_filters %}

{% with object as bookmark %}
  {% with bookmark_object=get_bookmark_object bookmark.content_type bookmark.object_id %}
    {% if bookmark.content_type.model == 'post' %}
      {% include 'content/post/object.html' with object=bookmark_object user_bookmark=bookmark %}
    {% elif bookmark.content_type.model == 'note' %}
      {% include 'content/note/object.html' with object=bookmark_object user_bookmark=bookmark %}
    {% endif %}
  {% endwith %}
{% endwith %}

我得到错误:

TemplateSyntaxError at /my-page/
'with' received an invalid token: 'bookmark.content_type'

我的问题是:

如何在with 语句中使用我的自定义get_bookmark_object 模板标签?一个带有代码的示例将帮助我澄清很多。

参考: Django's with built-in

【问题讨论】:

    标签: django django-templates django-template-filters


    【解决方案1】:

    你定义的是一个模板标签,你可以用{% … as … %}标签给模板标签产生的值赋值:

    {% get_bookmark_object bookmark.content_type bookmark.object_id as bookmark_object %}
        …

    【讨论】:

    • 谢谢!你是 100% 正确的。我想我不需要with
    猜你喜欢
    • 2012-03-31
    • 1970-01-01
    • 2021-07-13
    • 2022-11-25
    • 2015-01-20
    • 1970-01-01
    • 2012-03-15
    • 2020-11-06
    相关资源
    最近更新 更多