Jinja2模板未正确呈现if-elif-else语句

90

我正在尝试在jinja2模板中使用CSS设置文本颜色。在下面的代码中,如果变量包含字符串,则要将输出字符串设置为以特定字体颜色打印。每次生成模板时,由于else语句,它都会打印为红色,即使输出应该匹配前两个条件,我可以在表格生成时看到变量的输出,而它也是预期的。我知道我的css是正确的,因为默认情况下它以红色打印字符串。

我的第一个想法是将我检查的字符串用引号括起来,但那并没有起作用。接下来,我认为jinja没有扩展RepoOutput [RepoName.index(repo)] ,但是上面的循环正常工作, 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 %}

谢谢

1个回答

162
您正在测试变量errorAlready的值是否存在于RepoOutput [RepoName.index(repo)]中。如果这些变量不存在,则使用未定义对象

因此,您的ifelif测试都是错误的;在RepoOutput [RepoName.index(repo)]的值中没有未定义的对象。

我认为您想要测试某些字符串是否存在于值中:

{% 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>

{% set row_class = "good" if "Already" in RepoOutput[RepoName.index(repo)] else "error" %} 这个应该也可以工作。 - gnaanaa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接