2014-02-25 215 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:我完全錯過了那個編輯包含另一個改變! –