我有一个看起来像这样的列表:
[(u'Element1', u'Description1', u'Status1), (u'newElement2', u'newDescription2', u'newStatus2), (u'nextElement3', u'nextDescription3', u'nextStatus3), (u'anotherElement4', u'anotherDescription4', u'anotherStatus4)]
我有一个 ansible 剧本,它使用 jinja2 模板将列表呈现为文本文件。模板文件如下所示:
{% for item in description | batch(3, ' ') %}
{% for el in item %}
{{ el }}
{% endfor %}
{% endfor %}
但这返回的文本文件如下所示:
[u'Element1', u'Description1', u'Status1]
[u'newElement2', u'newDescription2', u'newStatus2]
[u'nextElement3', u'nextDescription3', u'nextStatus3]
[u'anotherElement4', u'anotherDescription4', u'anotherStatus4]
我希望报告看起来像这样:
Element1 Description1 Status1
newElement2 nextDescription2 newStatus2
nextElement3 nextDescription3 nextStatus3
anotherElement4 anotherDescription4 anotherDescription4
有没有办法删除 unicode 字符并以这种方式呈现列表?
例如:
{% for row in description %}
{% for cell in row %}
{{ "%-22s"|format(cell) }}
{%- endfor %}
{% endfor %}
收益 率:
Element1 Description1 Status1
newElement2 newDescription2 newStatus2
nextElement3 nextDescription3 nextStatus3
anotherElement4 anotherDescription4 anotherStatus4
但是要获得动态填充 - 取决于列中元素的最大长度 - 看起来像是一项更复杂的任务:{{ "%-22s"|format(cell) }}
可以替换为{{ "{0}".format(cell).ljust(width) }}
,其中width
可以是变量,但可能需要先进行另一个循环来收集长度。
你可以试试
{% for el in item %}
{% for e in el %}
{{ e }}
{% endfor %}
{% endfor %}
或者,如果您希望能够更改格式,请使用 html 表格