Jinja2:将一个列表中的项与另一个lis中的项进行比较

2024-04-23 15:10:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个主题列表:

list1 = [topic1, topic2, topic3, topic4, topic5, topic6]

我想对照这张单子核对另一张单子:

^{pr2}$

像这样:

{% if list2.items in list1 %}

其中列表2中的每个项目都在列表1中进行检查。如果列表2中的所有或任何项都在列表1中,则这是真的。我想这很简单,但我找不到任何有用的东西。在

完整示例:

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

**我在cms中工作,没有服务器端访问,所以我只有模板语言可以使用。在


Tags: in列表forifpost单子setlist2
2条回答

我不知道有什么Jinja2 built-in tests可以做到这一点,但是添加自己的很容易。在

假设您在一个名为template.j2的文件中有一个这样的模板:

Is l1 in l2: {% if l1 is subsetof(l2) %}yes{% else %}no{% endif %}

然后,您可以(在本例的同一目录中)有一个Python脚本来添加此检查:

^{pr2}$

请注意,测试函数的第一个参数在模板中的is子句之前传递,而第二个参数在括号内传递。在

应打印:

Is l1 in l2: yes

看看如何定义自定义测试here

只需创建自定义筛选器:

def intersect(a, b):
    return set(a).intersection(b)

env.filters['intersect'] = intersect

然后将其用作其他过滤器:

^{pr2}$

这是在Ansible中完成的。在

相关问题 更多 >