jinja2 how to remove trailing newline

后端 未结 6 1478
轮回少年
轮回少年 2021-01-31 01:36

I\'m using jinja 2 to output a yaml file but can\'t seem to get rid of a trailing newline and the end of a for loop. Eg the below

 - request:
        path: {{ p         


        
6条回答
  •  一向
    一向 (楼主)
    2021-01-31 02:17

    The accepted answer is only half of the solution, because it removes all newlines.

    You can avoid the trailing newline by first removing all newlines (using the minus signs at -%} and {%- in the for loop), and then inserting the desired newlines at the right place (using the loop.last condition).

    The following templates renders a dictionary, d, to as JSON text:

    {
        {% for key, value in d.items() -%}
        "{{ key }}": "{{ value }}"{{ ",
        " if not loop.last }}
        {%- endfor %}
    }
    

    For d = {'a':'1', 'b':'2'}, the template renders to

    {
        "a": "1",
        "b": "2"
    }
    

提交回复
热议问题