检查Django模板中的列表变量项是否存在 [英] Checking if something exists in items of list variable in Django template

查看:2268
本文介绍了检查Django模板中的列表变量项是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我传递给Django模板的部分列表。这些部分有不同的类型。我想在我的模板中说如果有这种类型的一部分,显示这一行,但是有一个问题。我基本上想做的是这样的。

  {%如果s.name ==社交 %} 
你好社交!
{%endif%}

但这当然不起作用。任何想法如何基本上在一行循环通过列表中的项目并做一个if语句?



其他信息:我可能有多个社会部分。我想在模板中做的是说如果有任何社会版块,显示这个div,如果没有,不要显示div。但是我不希望div重复,上面的代码将会发生什么。

解决方案

你会做的是创建一个模板获取的列表:

  l = [在部分的s.name] 

在模板中,使用:

  {%if'Social'in l%} 

试图把更多的逻辑放在比他们想要的模板更多的模板中。模板应该尽量少使用逻辑,而逻辑应该在填充模板的代码中。


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 %}

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?

ADDITIONAL INFO: I could potentially have multiple "Social" sections. What I'm trying to do in the template is say "if there are any social sections, display this div. If not, don't display the div." But I dont want the div to repeat, which is what would happen with the above code.

解决方案

Ideally what you would do is create a list that the template gets as such:

l = [s.name for s in sections]

And in the template, use:

{% 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆