Python (Jinja2) 变量里面的一个变量
问题描述:
我正在尝试在 Jinja2 模板(在 Ansible 中)中迭代字典.字典中的数组或键之一是 'abcd'
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'
此 {{ item.value.abcd.port }}
工作正常,但每个字典中的键 'abcd' 各不相同.
This {{ item.value.abcd.port }}
works fine, but key 'abcd' varies in each dictionary.
我希望使用变量nginx_dir"执行以下操作.
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 }}
答
为了在变量中使用变量,我不得不使用其中任何一个.
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 %}
我不想硬编码我的 Jinja2 模板,这正是我想要的.
I didn't wanted to hardcode my Jinja2 templates, this is exactly what I was looking for.