Python (Jinja2) variable inside a variable

2020-06-06 00:43发布

问题:

I am trying to iterate over a dictionary in a Jinja2 template (in Ansible). One of the arrays or keys in the dictionary is 'abcd'

This {{ item.value.abcd.port }} works fine, but key 'abcd' varies in each dictionary.

I am looking to do something like below using a variable 'nginx_dir'.

{% set nginx_dir = item.value.keys().1 %}
{% set my_port = item.value.nginx_dir.port %}

Or without using a variable at all, something like this

{{ item.value.[item.value.keys().1].port }}

回答1:

I had to use either of these to use a variable inside a variable.

{% set my_port = item.value.get(nginx_dir).port %}
{% set my_port = item.value[nginx_dir].port %}

I didn't wanted to hardcode my Jinja2 templates, this is exactly what I was looking for.