Jinja2中列表的唯一过滤器 [英] Unique Filter of List in Jinja2

查看:58
本文介绍了Jinja2中列表的唯一过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下YAML结构:

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

我正在尝试使用Jinja2获取插槽的唯一列表,即:

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

哪个给我:

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

但是,我似乎无法找到获取唯一列表的方法.

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

Ansible似乎具有可以执行此操作的唯一"过滤器.但是在这种情况下,我不使用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

有人可以建议实现这一目标的最佳方法吗?应该(或可以)使用Jinja2本地完成此操作,还是应该采用替代方法?

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?

推荐答案

自jinja2 2.10

在版本2.10中添加了unique过滤器.您可以查看更改日志

Since jinja2 2.10

A unique filter was added in version 2.10. You can check the change log and the PR.

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)

输出:

<li>1</li>

<li>2</li>

<li>3</li>

<li>4</li>

<li>5</li>

这篇关于Jinja2中列表的唯一过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆