【问题标题】:Jinja2 template not rendering if-elif-else statement properlyJinja2 模板未正确呈现 if-elif-else 语句
【发布时间】:2014-03-28 07:02:59
【问题描述】:

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

谢谢

【问题讨论】:

    标签: python css if-statement jinja2


    【解决方案1】:

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

    因此,您的 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 ... %}
    • &lt;/tr&gt; 标记移出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>
    

    【讨论】:

    • 我会研究类以供广泛使用,我只是在测试这个特定的表。感谢您的想法,我对 css 很陌生。
    • 现在可能不重要,但是“elif Already”行(也在 OP 中)缺少一个右方括号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 2019-08-28
    相关资源
    最近更新 更多