是否可以在Jinja模板中动态行

时间:2020-09-04 15:25:33

标签: ansible

我想基于文件中的数字行在jinja模板中添加行。 例如。我的文件有3行然后jinja模板应该如下所示。 假设我的行文件增加,那么应该在变红时将行自动添加到jinja模板中。 我正在从文件中计数

import re
def hidden_word(keyword, counter=0):
    dots = re.sub("[^\s]", '.', keyword[counter:])
    return keyword[:counter] + dots

hidden_word('test_word', counter=2)

2 个答案:

答案 0 :(得分:2)

只需在 set row = item.split(“”) 上添加一个新的for循环即可遍历该列表中的项目,而您永远不会必须使用列表索引。

{% for item in join_out.stdout_lines %}
<tr>
{%  set rows = item.split(" ") %}
{% for row in rows %}
  <td align="center">{{ row | replace('"','') }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>

答案 1 :(得分:1)

除去引号,然后首先分割行。然后只需创建表。例如

shell> cat playbook.yml
- hosts: localhost
  vars:
    join_out:
      stdout_lines:
        - '"A1" "B1"'
        - '"A2" "B2"'
  tasks:
    - set_fact:
        my_data: "{{ my_data|default([]) + [item.split(' ')] }}"
      loop: "{{ join_out.stdout_lines|
                map('regex_replace', my_regex, my_replace)|
                list }}"
      vars:
        my_regex: '"'
        my_replace: ''
    - copy:
        content: |
          <table>
          {% for line in my_data %}
          <tr>
          {%  for row in line %}
          <td align="center">{{ row }}</td>
          {% endfor %}
          </tr>
          {% endfor %}
          </table>
        dest: table.html

给予

shell> cat table.html
<table>
<tr>
<td align="center">A1</td>
<td align="center">B1</td>
</tr>
<tr>
<td align="center">A2</td>
<td align="center">B2</td>
</tr>
</table>