简体   繁体   English

从字典中筛选出密钥

[英]Filter out key from dictionary

Having dictionary (defined in map.jinja ) 具有字典(在map.jinja中定义)

{% set intellij = salt['grains.filter_by']({
    'default': {
        'orig_name': 'idea-IC-145.1617.8',
        'download_url': 'www.example.com',         
        'archive_format': 'tar',
        'archive_opts': 'xfz',
        'owner': 'root',
        'owner_link_location': '/blabla/bin/idea',
    },
}, merge=salt['pillar.get']('intellij')) %}

and some function definition accepting arguments almost the same as the dictionary's keys (let's assume the "function" is actually a macro) 以及一些接受参数的函数定义几乎与字典的键相同(假设“ function”实际上是一个宏)

{% macro some_macro(state_id, orig_name, download_url, archive_format, owner, archive_opts=None) %}

I would like to filter out some keys so that I can call it like this: 我想过滤掉一些键,以便可以这样称呼它:

{{ some_macro('some_state', **intellij) }}

I've tried various constructs, like: 我尝试了各种构造,例如:

{{ some_macro('intellij', **(intellij|rejectattr("owner_link_location"))) }}

which yields 产生

Jinja error: call() argument after ** must be a mapping, not generator

Dict-comprehension (instead of jinja filter) also doesn't work. Dict-comprehension(而不是Jinja过滤器)也不起作用。

How to achieve the aforementioned functionality (filtering out the key or at least calling the function with "extracted" and filtered dictionary in concise way)? 如何实现上述功能(以简洁的方式过滤掉键或至少使用“提取的”和过滤后的字典调用函数)?

The problem you encountered is described here . 你遇到的问题是描述在这里
There is a trick to work around which looks fine to me. 有一个解决方法,对我来说很好。

{% macro some_macro(state_id, orig_name, download_url, archive_format, owner, archive_opts=None) -%}
{% if kwargs | length >= 0 -%}
// implement your macro definition here
{% endif -%}
{% endmacro -%}

The point is that you have to call kwargs if you didn't consume all the variables in mapping. 关键是,如果未在映射中使用所有变量,则必须调用kwargs

Then call your macro as : 然后将您的宏称为:

{{ some_macro('some_state', **intellij) }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM