[英]Using Jinja2 Expression within Jinja2 Statement
Let's say I have the following Jinja2 variables: 假设我有以下Jinja2变量:
I would like to set a condition upon when the 'dev_ami' variable is equal to the 'dev_located_ami' variable. 我想为'dev_ami'变量等于'dev_located_ami'变量设置条件。 This would easily be done as shown in the following statement:
如以下语句所示,可以轻松完成此操作:
{% if dev_ami == dev_located_ami %}
... do some stuff
{% else %}
... do some other stuff
{% endif %}
But I would like to dynamically compare amis based on the deployment environment contained in a list ['dev','prod', etc...]. 但是我想根据列表['dev','prod'等...]中包含的部署环境动态比较amis。 The following contains a templating error since there is an expression within a statement as such -
{% {{ .. }} %}
: 以下包含模板错误,因为语句内有一个表达式,例如-
{% {{ .. }} %}
:
{% for env_type in ['dev','prod'] %}
{% if {{ env_type }}_ami == {{ env_type }}_located_ami %}
... do stuff
{% else %}
... do other stuff
{% endif %}
{% endfor %}
I have tried to set variables to represent the expressions I would like in the following code but unfortunately they are compiled literally as 'dev_ami' and 'dev_located_ami' whereas I would like them compiled to their corresponding variable values 'ami-123456' and 'ami-123456': 我试图在下面的代码中设置变量来表示我想要的表达式,但是不幸的是它们被字面地编译为“ dev_ami”和“ dev_located_ami”,而我希望它们被编译为相应的变量值“ ami-123456”和“ ami” -123456':
{% for env_type in ['dev','prod'] %}
{% set ami = "%s_ami"|format(env_type) %}
{% set located_ami = "%s_located_ami"|format(env_type) %}
{% if ami == located_ami %}
... do stuff
{% else %}
... do other stuff
{% endif %}
{% endfor %}
I have checked through various filters and so far have had no success. 我已经检查了各种过滤器,到目前为止还没有成功。 Would appreciate advice on getting this specific implementation to work properly.
希望获得有关此特定实现正常工作的建议。 Thank you in advance.
先感谢您。
I think you might be approaching the problem with the wrong datastructure in mind. 我认为您可能会想到错误的数据结构来解决问题。
Dynamically generating variable names in order to compare amis in different environemts sounds like a massive overkill to me. 为了比较不同环境中的amis,动态生成变量名对我来说听起来像是过大的杀伤力。 Are you familiar with lists & dictionaries?
您熟悉列表和词典吗?
Try to start from something like this (pseudocode): 尝试从这样的东西(伪代码)开始:
dict = { environments:
prod:
ami1: foo
ami1_located: foo
dev:
ami1: bar
ami1_located:baz
}
for env in dict[environments]:
if env[ami1] == env[ami1_located]:
[...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.