Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python (Jinja2) variable inside a variable

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 }}
like image 532
vikas027 Avatar asked Oct 06 '15 18:10

vikas027


1 Answers

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.

like image 121
vikas027 Avatar answered Sep 28 '22 23:09

vikas027