Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique Filter of List in Jinja2

I have the following YAML structure:

bri:
  cards:
    - slot: "1"
      subslot: "0"
      ports: 2
    - slot: "1"
      subslot: "1"
      ports: 2
    - slot: "1"
      subslot: "2"
      ports: 2
    - slot: "2"
      subslot: "0"
      ports: 2
    - slot: "2"
      subslot: "1"
      ports: 2

I am attempting to use Jinja2 to get a unique list of slots, i.e.:

['1', '2']

So far, I've managed to apply the following:

{{ bri.cards|map(attribute='slot')|list }}

Which gives me:

['1', '1', '1', '2', '2']

However, I don't seem to be able to find a way to get a unique list.

Ansible

Ansible appears to have a "unique" filter that can do this. But I'm not using Ansible in this case.

  • http://docs.ansible.com/ansible/playbooks_filters.html#set-theory-filters
  • ansible/jinja2 get unique subelements

My question

Can anyone suggest the best way to achieve this? Should (or can) this be done natively with Jinja2, or should I adopt an alternative approach?

like image 335
jonathan Avatar asked Nov 30 '22 15:11

jonathan


1 Answers

Since jinja2 2.10

A unique filter was added in version 2.10 (released 2017-11-08). You can check the change log and the PR.

Usage example

from jinja2 import Template


template = Template("""
  {% for x in a|unique %}
    <li>{{ x }}</li>
  {% endfor %}
""")

r = template.render(a=[1, 2, 3, 4, 1, 5, 4])

print(r)

Output:

<li>1</li>

<li>2</li>

<li>3</li>

<li>4</li>

<li>5</li>
like image 76
Edgar Ramírez Mondragón Avatar answered Dec 05 '22 13:12

Edgar Ramírez Mondragón