Jinja2模板没有正确渲染if-elif-else语句

Mat*_*tty 38 css python 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 %}
Run Code Online (Sandbox Code Playgroud)

谢谢

Mar*_*ers 70

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

因此,你if和你的两个elif测试都是假的; 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>
Run Code Online (Sandbox Code Playgroud)

我做的其他更正:

  • 用来{% elif ... %}代替{$ elif ... %}.
  • </tr>标签移出if条件结构,它总是需要在那里.
  • id属性周围加上引号

请注意,您很可能class在此处使用属性,而不是a 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>
Run Code Online (Sandbox Code Playgroud)