首页 > 解决方案 > 将 templatetag 建立为 django 变量

问题描述

我正在尝试在模板标记中过滤 django 查询集,如下所示:

@register.simple_tag
def splice(query, person_id):
    query2 = query.filter(personid=person_id)
    return query2

然后,在我的模板中,我想将新过滤的查询集传递到包含 html 文件中。这是我的尝试:

{% with splice df person_id as x %}
   {% include 'includes/file.html' with df=x %}

我怎样才能正确执行这个?或者有没有人有想法如何以更有效的方式进行?

标签: djangotemplatetags

解决方案


你不需要with那里;一个简单的标签可以使用 . 直接将其数据添加到上下文中as

{% splice df person_id as x %}

但是,这可能不是正确的方法。与其编写模板标签来为包含的模板添加上下文,不如使用包含标签,它负责将模板包含到特定上下文的整个过程。所以:

@register.inclusion_tag('template/file.html')
def splice_include(query, person_id):
    query2 = query.filter(personid=person_id)
    return {'df': x}

现在你可以直接使用它了:

{% splice_include df person_id %}

根本不需要单独include的。


推荐阅读