2014-02-25 175 views
14

我想在jinja2模板中使用css设置文本颜色。在下面的代码中,如果变量包含一个字符串,我想设置输出字符串以特定的字体颜色打印。每次生成的模板,虽然它在红色打印由于else语句,它永远不会看到前两个条件,即使输出应匹配,我可以告诉从变量输出是什么时,表生成,它是如预期。我知道我的CSS是正确的,因为默认情况下将字符串打印为红色。Jinja2模板不能正确渲染if-elif-else语句

我的第一个想法是把我正在检查的字符串括起来,但没有奏效。接下来是神社没有扩大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 %} 

感谢

+0

是'error'和'Already'意思是串在这里? –

+0

你的意思了'elif'标签与'{$'开始? –

+0

从逻辑上讲,'id = error'总是被设置,除非'已经在RepoOutput [RepoName.index(repo)'中为真;这可以让你在这里测试一个分支。 –

回答

27

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

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

我想你想测试,如果某些字符串是不是值:

{% 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> 
    
  • +0

    我会考虑广泛使用的类,我只是测试这一个特定的表。感谢您的想法,我对css相当陌生。 – Matty

    +0

    @MartijnPieters是的,我对'{%endif%}'不好。抱歉! – danilopopeye

    +1

    @danilopopeye:我完全错过了那个编辑包含另一个改变! –