建立templatetag为django变数

时间:2018-12-18 17:56:19

标签: django templatetags

我正在尝试在模板标签中过滤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 %}

如何正确执行此操作?还是有人对如何更有效地实现这一想法有想法?

2 个答案:

答案 0 :(得分:0)

您在那里不需要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

答案 1 :(得分:0)

您需要重新排列传递参数的方式。使用Django docs提供了一个很好的示例。然后,您可以从file.html调用templatetag。

调用文件 {% include 'includes/file.html' with df=df person_id=person_id %}

file.html {% load my_template_tags %} {{df|slice:person_id}}

相关问题