在自定义模板标签中搜索上下文

Search through context in custom templatetag

我目前正在使用自定义 templatetags 来减少我的模板代码。我实质上是将上下文从视图传递到标记,然后将其呈现到共享模板中。然而,我遇到了一个我无法解决的问题。

我传递给标记的视图的上下文每个都包含一个以 '_collection' 结尾的键。本质上,我需要遍历上下文并找到对应于该子字符串的 key/value 对,然后将其映射到标记上下文。

这是我使用的模板标签:

from django import template

register = template.Library()


@register.inclusion_tag('main/collection.html', takes_context=True)
def collection(context):
    ctx = {
        'is_create': context['is_create']
    }

    if '_collection' in context:
        # not sure how to get this into the context

    return ctx

基本上我只想通过使用该子字符串将该值正确映射到 templatetag 上下文。

如有任何帮助,我们将不胜感激。

感谢您的宝贵时间。

如果我对你的问题的理解正确,你想要的只是通过仅使用某些键(以 "_context" 结尾的键)从上下文创建映射

ctx = {
    key.split("_collection")[0]: value
    for key, value in context.flatten().items()
    if key.endswith("_collection")
}

这应该足够了。注意 key 上的拆分。它将 foo_collection 更改为 foo。如果不想这样,你可以直接使用密钥而不拆分。

在上下文中调用 flatten() 应该是 return 一个结合所有来源(视图和所有上下文预处理器)的上下文数据的字典。由于我们现在有一个字典,我们可以毫无问题地迭代它的项目。

然后您可以添加任何您想要添加的特定键

ctx['is_create'] = context['is_create']

或者,如果您不想调用 flatten,您可以遍历上下文并执行类似

的操作
ctx = {
    'is_create': context['is_create']
}
for key in context:
   if key.endswith("_collection"):
       ctx[key.split("_collection")[0]] = context[key]