k-rd k-rd - 22 days ago 7
Python Question

how to check keys variable exist and prevent printing line that key+value empty in jinja2 template

I have jinja2 template which get data variables from yaml in the form of 'keys : value'.

The issue is when I run jinja2 template, it will print the line that has empty 'value'.

How can I do so that it will not print the line that is empty. Otherwise, it will appear None.

For example;

-Template

set first {{ABC}}
set second {{DEF}}
set third {{GHI}}


-yaml data

ABC : data1
DEF :
GHI : data3


If I run this, it will state that;

set first data1
set second None
set third data3


I don't want it to be this way. I want it to print;

set first data1
set third data3


How to do that?by preventing line from being added if the variable is undefined.

Thanks,

Answer

You can use Jinja's {% if variable %} blocks - @Jalepeno112 answers it well for this question. However, if possible I would suggest parsing the YAML into a data structure like a dictionary in python and then using the data structure in the Jinja template.

This will give you the opportunity to clean the data in python and then send only the values that exist.

I am making an assumption here that the YAML is being passed via python to Jinja as you have also added python tag to the question.

Edit 1: There are multiple ways to achieve this but adding a simple example to show what I mean.

with open('tmp.yaml', 'r') as stream:
    try:
        yaml_input_data = yaml.load(stream)
    except yaml.YAMLError as exc:
        # handle error
        pass

print(yaml_input_data)
# {'ABC': 'data1', 'DEF': None, 'GHI': 'data3'}

for k, v in yaml_input_data.items():
    if v is None:
        yaml_input_data.pop(k)

# Now pass yaml_input_data to the Jinja template
print(yaml_input_data)
#{'ABC': 'data1', 'GHI': 'data3'}