我正在尝试在 jinja2 模板中使用 css 设置文本颜色。在以下代码中,如果变量包含字符串,我想将输出字符串设置为以特定字体颜色打印。每次生成模板时,尽管由于 else 语句而以红色打印,但即使输出应该匹配,它也永远不会看到前两个条件,我可以知道当表生成时变量的输出是什么并且它是预期的.我知道我的 css 是正确的,因为默认情况下以红色打印字符串。
我的第一个想法是将要检查的字符串括在引号中,但这不起作用。接下来是 jinja 没有扩展 RepoOutput[RepoName.index(repo)]
但上面的 for 循环有效, RepoName
被正确扩展。我知道如果我添加大括号,它将打印我相当肯定会破坏模板或不起作用的变量。
我尝试查看这些站点并浏览了全局表达式列表,但找不到任何与我相似的示例或进一步研究的方向。
http://jinja.pocoo.org/docs/templates/#if
http://wsgiarea.pocoo.org/jinja/docs/conditions.html
{% for repo in RepoName %}
<tr>
<td> <a href="http://mongit201.be.monster.com/icinga/{{ repo }}">{{ repo }}</a> </td>
{% if error in RepoOutput[RepoName.index(repo)] %}
<td id=error> {{ RepoOutput[RepoName.index(repo)] }} </td> <!-- I want this in green if it is up-to-date, otherwise I want it in red -->
{% elif Already in RepoOutput[RepoName.index(repo)] %}
<td id=good> {{ RepoOutput[RepoName.index(repo)] }} </td> <!-- I want this in green if it is up-to-date, otherwise I want it in red -->
{% else %}
<td id=error> {{ RepoOutput[RepoName.index(repo)] }} </td> <!-- I want this in green if it is up-to-date, otherwise I want it in red -->
</tr>
{% endif %}
{% endfor %}
谢谢
最佳答案
您正在测试变量的值 error
和 Already
存在于 RepoOutput[RepoName.index(repo)]
.如果这些变量不存在,那么 undefined object被使用了。
你的两个if
和 elif
因此测试是错误的; RepoOutput[RepoName.index(repo)] 的值中没有 undefined object 。
我认为您想测试某些 字符串 是否在值中:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo)] %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
我所做的其他更正:
- 已使用
{% elif ... %}
而不是{$ elif ... %}
. - 移动了
</tr>
标记出if
条件结构,它需要一直存在。 - 在
id
周围加上引号属性
请注意,您很可能希望使用 class
属性,而不是 id
,后者的值必须在您的 HTML 文档中是唯一的。
就个人而言,我会在这里设置类值并减少一点重复:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
关于python - Jinja2 模板未正确呈现 if-elif-else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22024661/