JSu*_*Sum 3 python compare items list jinja2
我有一个主题列表:
list1 = [topic1, topic2, topic3, topic4, topic5, topic6]
Run Code Online (Sandbox Code Playgroud)
我想根据此列表检查另一个列表:
list2 = [topic2, topic4, topic6]
Run Code Online (Sandbox Code Playgroud)
像这样:
{% if list2.items in list1 %}
Run Code Online (Sandbox Code Playgroud)
在 list1 中检查 list2 中的每个项目。如果 list2 中的所有或任何项目都在列表 1 中,则为 True。我认为这很简单,但我无法找到任何对此有帮助的信息。
完整示例:
{% set list1 = [topic2, topic4, topic6] %}
{% for post in posts %}
{% set list2 = [topic1, topic2, topic3, topic4, topic5, topic6] %}
{% for topic in list2 %}
{% if topic in list1 %}
{# output of post list based on conditions #}
{% endif %}
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
** 我在没有服务器端访问的 cms 中工作,所以我只有模板语言可以使用。
只需创建一个自定义过滤器:
def intersect(a, b):
return set(a).intersection(b)
env.filters['intersect'] = intersect
Run Code Online (Sandbox Code Playgroud)
然后将其用作任何其他过滤器:
{% if list1 | intersect(list2) %}
hello
{% else %}
world
{% endif%}
Run Code Online (Sandbox Code Playgroud)