Search code examples
pythonflaskjinja2

Access Jinja2 dict_keys values inside templete


I am trying to figure out why in Jinja2 the following code does not work. I am setting the keys of a dictionary inside Jinja2 this dictionary has only one key and I want to access the key name however calling the tc_class_name variable inside Jinja2 only returns the following dict_keys(['TestEVPNSingleFlow'])) I have tried to use list index {{tc_class_name[0]}) but some reason that returns nothing. However I tried doing that in Python and using list index works. Also if I do a Jinja2 for loop over tc_class_name that does work but would prefer a better solution because I will run into other issues if I use a Jinja2 for loop

Jinja2 code

{% set tc_class_name = chart_data[0]['TestCaseData'].keys() %}
{{tc_class_name})

# returning the following when i print out tc_class_name variable inside the HTML
# dict_keys(['TestEVPNSingleFlow']))

Normal Python code

In [17]: tc_class_name = chart_data[0]['TestCaseData'].keys()

# This is what I am trying to do via Jinja2 not sure why this is not working for Jinja
In [19]: tc_class_name[0]
Out[19]: 'TestEVPNSingleFlow'

Solution

  • So as I figured the solution was quite easy just needed to return the dict_keys as a true list for jinja2 to understand. Below is what I ended up doing.

    {% set tc_class_name = chart_data[list_len]['TestCaseData'].keys() | list %}