Search code examples
jinja2jinja2-cli

Condition based on the three first letters of a string?


In my Jinja template, model.DataType value can be user defined or built in. My requirenement is if model.DataType start with the three letters ARR, then do a specific operation.

Example of values:

  • ARRstruct124
  • ARR_int123
  • ARR123123
  • CCHAR
  • UUINT
  • etc.
{% set evenDataType = model.eventDataType %}
{%if evenDataType | regex_match('^ARR', ignorecase=False) %}
  // do the operation
{%else%}
  // do the operation
{% endif %}

With this template, I am getting the error

{%if evenDataType | regex_match('^ARR', ignorecase=False) %}
jinja2.exceptions.TemplateAssertionError: no filter named 'regex_match'


Solution

  • There is indeed no regex_match filter in the Jinja builtin filters. You might have found some examples using it, but this is an additional filter provided by Ansible, so it won't work outside of Ansible.

    This said, your requirement does not need a regex to be fulfilled, you can use the startswith() method of a Python string.

    So, you template should be:

    {% set evenDataType = model.eventDataType %}
    {% if evenDataType.startswith('ARR') %}
      `evenDataType` starts with 'ARR'
    {% else %}
      `evenDataType` does not starts with 'ARR'
    {% endif %}