检查 Django 模板中的列表变量项中是否存在某些内容 [英] Checking if something exists in items of list variable in Django template
问题描述
我有一个传递给 Django 模板的部分列表.这些部分有不同的类型.我想在我的模板中说如果有这种类型的部分,显示这一行",但是有问题.我基本上想做的是这个.
I have a list of sections that I pass to a Django template. The sections have different types. I want to say "if there is a section of this type, display this line" in my template, but having an issue. What I'm basically trying to do is this.
{% if s.name == "Social" for s in sections %}
Hello Social!
{% endif %}
但这当然行不通.知道如何基本上在一行中遍历列表中的项目并执行 if 语句吗?
But of course that's not working. Any idea how to basically in one line loop through the items in a list and do an if statement?
附加信息:我可能有多个社交"部分.我试图在模板中做的是说如果有任何社交部分,显示这个 div.如果没有,不要显示这个 div."但我不希望 div 重复,这就是上面代码会发生的情况.
推荐答案
理想情况下,您要做的是创建一个模板获取的列表:
Ideally what you would do is create a list that the template gets as such:
l = [s.name for s in sections]
在模板中,使用:
{% if 'Social' in l %}
您正试图在模板中加入比预期更多的逻辑.模板应该尽量少用逻辑,而逻辑应该在填充模板的代码中.
You're trying to put more logic into a template than they are meant to have. Templates should use as little logic as possible, while the logic should be in the code that fills the template.
这篇关于检查 Django 模板中的列表变量项中是否存在某些内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!