Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jinja2 how to remove trailing newline

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: {{ path }}         headers:           origin: 'somedomain.com'           user-agent: 'agent'           referer: 'some.domain.com'           authority: 'somedomain.com'         querystring:           {% for key, value in querystring.items() -%}           {{ key }}: '{{ value }}'           {% endfor %}       response:         content:           file: {{ content }} 

gives me the output:

- request:     path: /some/path     headers:       origin: 'somedomain.com'       user-agent: 'agent'       referer: 'somedomain.com'       authority: 'somedomain.com'     querystring:       postcode: 'xxxxxx'       houseNo: '55'    response:     content:       file: address.json 

With an additional unwanted blank line after houseNo. How do I get rid of this line?

like image 281
Yunti Avatar asked Apr 26 '16 16:04

Yunti


2 Answers

Change your loop to strip whitespace from the top AND bottom of the output (notice extra - at the for loop close):

{% for key, value in querystring.items() -%}   {{ key }}: '{{ value }}' {%- endfor %} 

In my tests (using https://github.com/abourguignon/jinja2-live-parser), the - must come after the first {%, not before the last to achieve what you're asking for.

Docs: https://jinja.palletsprojects.com/en/latest/templates/#whitespace-control

like image 63
tknickman Avatar answered Sep 30 '22 11:09

tknickman


I think you can get rid of it using the whitespace control feature. Thus I would modify the endfor block to {% endfor -%}

See if that does it!

like image 41
Scratch'N'Purr Avatar answered Sep 30 '22 09:09

Scratch'N'Purr