1. 程式人生 > >freemarker中ftl語言中??、?has_content、!、?if_exists的區別

freemarker中ftl語言中??、?has_content、!、?if_exists的區別

最近在專案中,出現了一個bug,一開始用的??來判斷是否為空,但是報錯了,改成?has_content就沒錯了。

?? tells if the left hand operand’s value is missing (means it’s Java null or you have an undefined variable there), and gives back false (missing) or true (not missing) accordingly.

?has_content is very much like ??, except it also returns false for an empty string or empty list or empty map. (It doesn’t return false for a 0, boolean false, etc.)

! is used to give a default value when a value is missing, like color!”no color”. If you omit the right hand operand of !, then the default value is an empty string and empty sequence and empty hash on the same time.

?if_exists is the old way of writing ??. Don’t use it.

大意如下:
?? 判斷左側的變數是否丟失,相當於java中的null的判斷,或者這個變數是否未定義。
?has_content 非常像??,但是它同時也會對空字串或空list或空map進行判斷。
! 用來給變數一個預設值,例如color!”no color”
?if_exists 是??的老寫法,現在不推薦使用。