Conditional substring in a Jinja2 template

Moshe picture Moshe · Jan 22, 2017 · Viewed 47.7k times · Source

When deploying with ansible, There's 1 specific case where I need to strip a string of a trailing -p substring.

The string somemachine-prod-p should become somemachine-prod only if the -p is at the end.

The substring function I saw I can use with Jinja does not fulfill my needs as I need to strip the end of the string, not the start.

Ideas?

Answer

Moshe picture Moshe · Jan 22, 2017

Found it.

If anyone wants to know:

{% if name.endswith('-p') %}
{{ name[:-2] }}
{% else %}
{{ name }}
{% endif %}