代码之家  ›  专栏  ›  技术社区  ›  clay

Jinja2字符串附加?[副本]

  •  0
  • clay  · 技术社区  · 6 年前

    以下连接了三个字符串的列表:

    > Template('Hello {{ my_list | join(", ") }}!').render(my_list=['a', 'b', 'c'])
    'Hello a, b, c!'
    

    以下内容不起作用,但说明了我要做的事情:

    Template('Hello {{ my_list | append(":8080") | join(", ") }}!').render(my_list=['a', 'b', 'c'])
    

    下面是我想做的Python等价物:

    ", ".join([x + ":8080" for x in ['a', 'b', 'c']])
    

    虽然在Python中测试Jinja2表达式是最简单的,但我最终还是需要我的Jinja2表达式在Ansible剧本中工作,如以下Ansible片段:

      - name: "join without append"
        debug: msg="test={{ item | join(',') }}"
        with_items:
          - ["a", "b", "c"]
    
      - name: "this doesn't work"
        debug: msg="test={{ (item + ':8080') | join(',') }}"
        with_items:
          - ["a", "b", "c"]
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Baptiste Mille-Mathias    6 年前

    你必须这样做

    - hosts: localhost
      gather_facts: no
      tasks:
          - name: "this does work"
            debug:
              msg: "test={{ (item | join(',')) + ':8000'  }}"
            with_items:
              - ["a", "b", "c"]
    

    先连接,然后用字符串连接

    这给了你期望的结果

    PLAY [localhost] ******************************************************
    
    TASK [this does work] *************************************************
    ok: [localhost] => (item=None) => {
        "msg": "test=a:8000"
    }
    ok: [localhost] => (item=None) => {
        "msg": "test=b:8000"
    }
    ok: [localhost] => (item=None) => {
        "msg": "test=c:8000"
    }