Jinja: 允许地图过滤器检索多个项目

创建于 2016-02-29  ·  4评论  ·  资料来源: pallets/jinja

目前, map函数只能这样使用:

[{'path':'/var/file1', 'mtime': '123', 'mode': '600',...},{'path':'/var/file2', 'mtime': '123', 'mode': 644, ...}]|map(attribute='path')

随着回归

['/var/file1', '/var/file2']

(文档:http://jinja.pocoo.org/docs/dev/templates/#map)

我想提议允许这样做:

[{'path':'/var/file1', 'mtime': '123', 'mode': '600',...},{'path':'/var/file2', 'mtime': '123', 'mode': 644, ...}]|map(attribute=['path', 'mtime'])

或者

[{'path':'/var/file1', 'mtime': '123', 'mode': '600',...},{'path':'/var/file2', 'mtime': '123', 'mode': 644, ...}]|map(attributes=['path', 'mtime'])

哪个应该返回

[{'path':'/var/file1', 'mtime': '123'},{'path':'/var/file2', 'mtime': '123'}]

您已经可以看到这有什么用处:操作一个字典列表,以便这些字典只保留一组有限的属性。

最有用的评论

如果有人仍然需要这个,您可以使用以下代码(放入playbooks/filter_plugins/mapattributes.py ):

#!/usr/bin/env python
class FilterModule(object):
  def filters(self):
    return { 'mapattributes': self.mapattributes }

  def mapattributes(self, list_of_dicts, list_of_keys):
    l = []
    for di in list_of_dicts:
      newdi = { }
      for key in list_of_keys:
        newdi[key] = di[key]
      l.append(newdi)
    return l

使用方式:

ansible_mounts | mapattributes(['mount', 'size_total', 'size_available',])

所有4条评论

会喜欢这个功能。

我不清楚为什么模板中需要这样做。 只需遍历字典并使用您需要的属性就可以完成同样的事情。 如果您需要不同的数据,最好在渲染之前在 Python 中进行操作。 我可能_可能_看到它返回元组的用途。

如果有人仍然需要这个,您可以使用以下代码(放入playbooks/filter_plugins/mapattributes.py ):

#!/usr/bin/env python
class FilterModule(object):
  def filters(self):
    return { 'mapattributes': self.mapattributes }

  def mapattributes(self, list_of_dicts, list_of_keys):
    l = []
    for di in list_of_dicts:
      newdi = { }
      for key in list_of_keys:
        newdi[key] = di[key]
      l.append(newdi)
    return l

使用方式:

ansible_mounts | mapattributes(['mount', 'size_total', 'size_available',])

为什么此问题已关闭且 Nee6ione 解决方案未正式实施? 如果在没有任何额外插件的情况下支持它,那将会简单得多

此页面是否有帮助?
0 / 5 - 0 等级

相关问题

The-Compiler picture The-Compiler  ·  4评论

AMDmi3 picture AMDmi3  ·  4评论

jp-costa picture jp-costa  ·  5评论

mtrstudio picture mtrstudio  ·  5评论

guettli picture guettli  ·  5评论