2012-09-27 45 views
8

鑑於我有兩個變量{{ profile }},其值爲「test」,而{{ element.author }}的值爲「test」。在jinja2中,當我嘗試使用if比較它們時,什麼也沒有顯示出來。我做的比較如下:比較jinja2模板中的兩個變量

{% if profile == element.author %} 
{{ profile }} and {{ element.author }} are same 
{% else %} 
{{ profile }} and {{ element.author }} are **not** same 
{% endif %} 

我得到的輸出test and test are not same哪些錯誤,我怎麼能比?

+0

嘗試輸入值:{{[profile,element.author]}} – defuz

+0

意外發布。這個表達式應該表示變量。 – defuz

回答

2

profileelement.author不是相同類型,否則不相等。但是,它們在轉換爲字符串時確實會輸出相同的值。你需要正確地比較它們或者改變它們的類型是相同的。

+1

我只是想做一些字符串比較,該怎麼做? – user1629366

+0

也許:'str(profile)== str(element.author)'?不知道你的數據和代碼的所有類型和其他事情,我不能說。 – mjibson

1

您可以使用jinja2可用的許多built in tests之一來檢查變量的類型。例如string()number()。我有同樣的問題,我意識到這是類型。

8

我有同樣的問題,具有整數值的兩個變量在相同的值時不相同。

是否有任何方式使這項工作以任何方式。 也試圖使用str()== str()或int()== int(),但總是有一個未定義的錯誤。

UPDATE

找到解決方案: 只需使用過濾器,如{{ var|string() }}{{ var|int() }} https://stackoverflow.com/a/19993378/1232796

讀取DOC它可以在這裏http://jinja.pocoo.org/docs/dev/templates/#list-of-builtin-filters

你的情況,找到你想要做

{% if profile|string() == element.author|string() %} 
{{ profile }} and {{ element.author }} are same 
{% else %} 
{{ profile }} and {{ element.author }} are **not** same 
{% endif %}