django - 将 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 %}
我怎样才能正确执行这个?或者有没有人有想法如何以更有效的方式进行?
解决方案
你不需要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
的。
推荐阅读
- python - 冻结除输出/logits 之外的所有层
- android - 当我将 ListView 放在列中时,我得到“引发了另一个异常:未布置 RenderBox”
- python-2.7 - 如何从与当前脚本的父目录平行的目录导入 .py 文件?
- ruby - Ruby 的块语法的起源是什么?
- javascript - 在返回的内部函数中访问参数对象
- r - 我可以用一个表达式引用多个正则表达式项吗?
- api - 使用 fetch api 调用带有 keepalive 的 POST 请求时,预检请求失败
- batch-file - 如何使用命令行更改 SRP 安全级别
- ruby-on-rails - 使用 Solr Sunspot 索引关联模型 - Rails
- typescript - 在单击链接之前和之后使用包含之类的内容验证文本