【问题标题】:Django template language "If" statement with many "and"Django 模板语言“If”语句带有许多“and”
【发布时间】:2021-06-06 23:08:57
【问题描述】:

基本上我想根据某些变量是否有内容向 div 添加一个类。

这是 If 语句:

<div class="search__container
    {% if images == true and blogs != True and parks != True %} 
        only-images 
    {% elif blogs == true and images != True and parks != True %} 
        only-blog
    {% elif parks == true and blogs != True and images != True %} 
        only-parks
    {% elif parks == true and blogs == true and images != True %} 
        only-parks-blogs
    {% elif parks == true and images == true and blogs != True %} 
        only-parks-images
    {% elif images == true and blogs == true and parks != True %} 
        only-images-blogs 
    {% endif %}"
>

这样它在任何情况下都不会添加任何类。

如果我改为删除 == 并将 != 替换为 is not 它将始终将第一个 if 设为 True 并添加类 only-images

【问题讨论】:

  • 为什么有些“True”没有大写?
  • @AlexandrTatarinov 我把它们大写了,问题仍然存在
  • 一般可以去掉'True'。只需if images 而不是if images == True。对于负面使用and not blogs
  • 一般来说,复杂的条件可以在views.py中完成,并在“上下文”中传递给你的模板。然后你可以检查单个布尔值,如“images_no_blogs_no_parks”。 “images_blogs_no_parks”等也意味着如果需要,您可以在其他地方重用这些条件

标签: python django if-statement


【解决方案1】:

不再建议在 python 中使用 == 和 != 和布尔 True/False。试试这个

<div class="search__container
    {% if images and not blogs and not parks %} 
        only-images 
    {% elif blogs and not images and not parks %} 
        only-blog
    {% elif parks and not blogs and not images %} 
        only-parks
    {% elif parks and blogs and not images %} 
        only-parks-blogs
    {% elif parks and images and not blogs %} 
        only-parks-images
    {% elif images and blogs and not parks %} 
        only-images-blogs 
    {% endif %}"
>

否则,考虑将这些条件放入传递给模板 (views.py) 的上下文中的单行布尔变量中,并验证“if images_no_logs_no_parks”等

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 2020-01-20
    相关资源
    最近更新 更多