Jinja2 templates, remove the carriage return

Viewed 392

I use Jinja2 templates for a lot of network device configurations but now I need to make a specific line of names for reporting purposes.

A Jinja2 script I use is as follows

{% for name in names -%}
{{name}} OR 
{% endfor -%}

It gives me

name1 OR
name2 OR
name3 OR

that in a text I make it look like what I need is "name1 OR name2 OR name3 OR" then "name1 OR name2 OR name3"

I am trying to research on creating a Jinja2 that will take me close or to the final format that I need.

Could someone help me with this, It would be greatly appreciated.

2 Answers

You can use loop.last to prevent outputting OR within the last iteration and use - to remove the carriage returns.

{% for name in names -%}
{{name}}{{ " OR " if not loop.last else "" -}}
{% endfor -%}

You need to use the {%- as start tag in order to drop whitespace for previous expression:

from jinja2 import Template

template = '''
{% for name in names -%}
{{name}} OR
{%- endfor -%}
'''
print (Template(template).render(names=['a', 'b', 'c']))

This returns following, which is probably not what you actually wanted.. :)

<newline>
a ORb ORc OR

So in order to get the wanted result there are at least two following options for template:

{{ names | join(' OR ') }}

or even shorter variant:

{{ " OR ".join(names) }}
Related