Python (Jinja2) 变量里面的一个变量 [英] Python (Jinja2) variable inside a variable

查看:26
本文介绍了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.

这篇关于Python (Jinja2) 变量里面的一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆