【问题标题】:Comparing corresponding elements of two lists in Django Template比较Django模板中两个列表的对应元素
【发布时间】:2021-06-22 07:14:00
【问题描述】:

我有两个大小相同的列表,如下所示:

change_list = ['none', 'M', 'D', 'none]

print_list = ['examples', 'app.py', 'list.fr', 'template']

我通过视图传递它们,我需要知道第一个列表中的值是什么,以便我可以根据第一个列表中的内容以不同的颜色显示第二个列表的元素。 例如,由于第一个列表中的“M”,我需要在模板中将“app.py”显示为橙色。

我已经四处搜索,但我不知道如何做到这一点。我试图将列表的 len 作为范围传递给这样的视图:

{% for i in len%}
    {% if changes_list.i == "M" %}
        <p style="color:orange;"> {{print_list.i}}</p>
    {% endif %}
{% endfor %}

但它没有用。

我不确定我是否正确地提出了这个问题,但我不确定如何解释这个问题。

提前谢谢你。

【问题讨论】:

  • 您想要的是根据 change_list 中的相应项目(相同索引)格式化 print_list 中的项目?如果是,请在下面查看我的答案。
  • 你的答案是正确的!谢谢!
  • 为了清楚起见,您应该将标题更改为“比较 Django 模板中两个列表的相应元素”这一行。不完美,但有助于将来搜索相同的问题。

标签: python python-3.x django list django-templates


【解决方案1】:

您的语法已关闭

这是一个简单的解决方案:

我们遍历列表并检查 i 是否等于“M”

{% for i in change_list %}
    {% if i == "M" %}
       <p>I</p>
    {% else %}
        <p>I Not == M</p>
    {% endif %}
{% endfor %}

如果您想比较这两个列表:

{% for i in change_list %}
    {% for x in print_list %}
      {% if i == x %}
       <p>I</p>
      {% else %}
        <p>I Not == X</p>
      {% endif %}
  {% endfor %}
{% endfor %}

【讨论】:

  • 这可能是因为我对标题的措辞,但这不是我想要的。接受的答案解决了我的问题。无论如何,感谢您的贡献!
【解决方案2】:

我会像下面这样试一试。警告,未经测试的代码;)

在你看来:

change_list = ['none', 'M', 'D', 'none']
print_list = ['examples', 'app.py', 'list.fr', 'template']
template_list = list(zip(change_list, print_list))

您只需将 template_list 传递给您的模板。

在您的模板中:

{% for i in template_list%}
    {% if i.0 == "M" %}
        <p style="color:orange;"> {{i.1}}</p>
    {% endif %}
{% endfor %}

你应该很好。

请注意,在视图中我使用 list() 和 zip(),因为我不知道 zip 对象是否可以在 Django 模板中工作。不用它也可以随意测试。

【讨论】:

  • 谢谢!这正是我想要的! zip 对象也适用于 Django 模板。
  • 很高兴它有帮助。感谢您返回 zip 对象。
猜你喜欢
  • 2019-12-07
  • 2020-07-04
  • 1970-01-01
  • 1970-01-01
  • 2015-11-06
  • 2014-01-07
  • 1970-01-01
相关资源
最近更新 更多