Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional substring in a Jinja2 template

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?

like image 697
Moshe Avatar asked Jan 22 '17 12:01

Moshe


People also ask

How do you write an if statement in Jinja?

In-line conditional statements​ Jinja in-line conditionals are started with a curly brace and a % symbol, like {% if condition %} and closed with {% endif %} . You can optionally include both {% elif %} and {% else %} tags.

How are variables in Jinja2 templates specified?

A Jinja template doesn't need to have a specific extension: . html , . xml , or any other extension is just fine. A template contains variables and/or expressions, which get replaced with values when a template is rendered; and tags, which control the logic of the template.


1 Answers

Found it.

If anyone wants to know:

{% if name.endswith('-p') %} {{ name[:-2] }} {% else %} {{ name }} {% endif %} 
like image 92
Moshe Avatar answered Sep 19 '22 11:09

Moshe