Python 当key是一个变量时,如何从jinja中的字典中获取值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18830393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:58:46  来源:igfitidea点击:

How to get values from dictionary in jinja when key is a variable?

pythonvariablesdictionaryjinja2substitution

提问by tytk

I'm trying to retrieve entries from a python dictionary in jinja2, but the problem is I don't know what key I want to access ahead of time - the key is stored in a variable called s.course. So my problem is I need to double-substitute this variable. I don't want to use a forloop because that will go through the dictionary way more than is necessary. Here's a workaround that I created, but it's possible that the s.coursevalues could change so obviously hard-coding them like this is bad. I want it to work essentially like this:

我正在尝试从 jinja2 中的 python 字典中检索条目,但问题是我不知道我想提前访问哪个键 - 键存储在一个名为s.course. 所以我的问题是我需要双重替换这个变量。我不想使用for循环,因为它会比必要的更多地通过字典方式。这是我创建的一种解决方法,但s.course值可能会发生变化,很明显,像这样对它们进行硬编码是不好的。我希望它基本上像这样工作:

{% if s.course == "p11" %}
    {{course_codes.p11}}
{% elif s.course == "m12a" %}
    {{course_codes.m12a}}
{% elif s.course == "m12b" %}
    {{course_codes.m12b}}
{% endif %}

But I want it to look like this:

但我希望它看起来像这样:

{{course_codes.{{s.course}}}}

Thanks!

谢谢!

采纳答案by R. Max

You can use course_codes.get(s.course):

您可以使用course_codes.get(s.course)

>>> import jinja2
>>> env = jinja2.Environment()
>>> t = env.from_string('{{ codes.get(mycode) }}')
>>> t.generate(codes={'a': '123'}, mycode='a').next()
u'123'

回答by onlyanegg

I'm using Jinja with Salt, and I've found that something like the following works well:

我正在将 Jinja 与 Salt 一起使用,我发现类似以下内容的效果很好:

{% for role in pillar.packages %}
  {% for package in pillar['packages'][role] %}
    install_{{ package }}:
      pkg.installed:
        - name: {{ package }}
  {% endfor %}
{% endfor %}

That is, use the more verbose [ ]syntax and leave the quotes out when you need to use a variable.

也就是说,[ ]当您需要使用变量时,使用更详细的语法并省略引号。

回答by Mike Vella

There is no need to use the dot notation at all, you can do:

根本不需要使用点符号,你可以这样做:

"{{course_codes[s.course]}}"