Jinja2: Compare items in one list to items in another list

Viewed 6150

I have a list of topics:

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

I would like to check another list against this list:

list2 = [topic2, topic4, topic6]

something like this:

{% if list2.items in list1 %}

where each item from list2 is checked for in list1. if all or any of the items from list2 are in list 1 then it's True. I figured this would be simple but I can't seam to find anything helpful about this.

Full example:

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

** I am working in a cms with out server side access so I only have the templating language to work with.

2 Answers

Just create a custom filter:

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

env.filters['intersect'] = intersect

And then use it as any other filter:

    {% if list1 | intersect(list2) %}
        hello
    {% else %}
        world
    {% endif%} 

This is how it's done in Ansible.

I am not aware of any Jinja2 built-in tests that can do this, but it's easy to add your own.

Let's say you have a template like this in a file called template.j2:

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

You can then (in the same directory for this example), have a Python script that adds this check:

import jinja2


def subsetof(s1, s2):
    return set(s1).issubset(set(s2))


loader = jinja2.FileSystemLoader(".")
env = jinja2.Environment(loader=loader)
env.tests["subsetof"] = subsetof

template = env.get_template("template.j2")
print(template.render(l1=[1, 2], l2=[1, 2, 3]))

Note that the first argument of the test function is passed before the is clause in the template, while the second argument is passed within the brackets.

This should print:

Is l1 in l2: yes

Take a look at how to define custom tests here

Related