[英]Jinja2 template not rendering if-elif-else statement properly
我正在嘗試在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 %}
謝謝
您正在測試RepoOutput[RepoName.index(repo)]
是否存在變量 error
和Already
的值。 如果這些變量不存在,則使用未定義的對象 。
因此,您的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>
我所做的其他更正:
{% elif ... %}
代替{$ elif ... %}
。 </tr>
標記移出if
條件結構,它必須始終存在。 id
屬性周圍加上引號 請注意,您最有可能在這里使用class
屬性,而不是id
,后者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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.