freemarker中ftl语言中??、?has_content、!、?if_exists的区别

最近在项目中,出现了一个bug,一开始用的??来判断是否为空,但是报错了,改成?has_content就没错了。

在网上查找原因后,总结如下:
原解答地址:
https://stackoverflow.com/questions/23552151/difference-between-has-content-if-exists-in-freemarker

?? 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 是??的老写法,现在不推荐使用。

猜你喜欢

转载自blog.csdn.net/u010398838/article/details/79978266