如何将自定义模板标签与 Django 的内置"with"标签结合使用?



我有这样一个简单的标签:

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的内置

您定义的是模板标记,您可以将模板标记产生的值分配给{% … as … %}标记:

{% get_bookmark_object bookmark.content_type bookmark.object_idas bookmark_object%}
…

相关内容

最新更新