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

标签 python css if-statement jinja2

我正在尝试在 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 %}

谢谢

最佳答案

您正在测试变量的值 errorAlready存在于 RepoOutput[RepoName.index(repo)] .如果这些变量不存在,那么 undefined object被使用了。

你的两个ifelif因此测试是错误的; 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/

相关文章:

MYSQL IF (SELECT) 查询返回多行

c# - while 语句忽略响应值

python - 在哪里可以下载带有 psycopg2 for Windows 的二进制鸡蛋?

javascript - 如何在没有类/id 的情况下获得 div 的明确子级

python - 保存多个csv文件并从数据集中加载图像

html - 导航栏隐藏我页面的请求

css - readthedocs.org 中的特殊 "note"框是如何制作的?

javascript - 未知的 if 语句在 javascript 中

python - Instant search with Whoosh - 使用 Woosh 输出 JSON 结果索引和搜索 MySQL 表

python - 如何在 PyCharm 中进行远程调试