freeMaker null值處理
以下引用官方描述:
引用
The FreeMarker template language doesn't know the Java language null at all. It doesn't have null keyword, and it can't test if something is null or not.
1.判斷是否存在,通過exists關鍵字或者"??"運算子。都將返回一個布林值
user.name?exists
user.name??
-
<#if user.name?exists>
-
//TO DO
-
</#if>
-
<#if user.age??>
-
//TO DO
-
</#if>
2.忽略null值
假設前提:user.name為null
${user.name},異常
${user.name!},顯示空白
${user.name!'vakin'},若user.name不為空則顯示本身的值,否則顯示vakin
${user.name?default('vakin')},同上
${user.name???string(user.name,'vakin')},同上
! :default value operator,語法結構為:unsafe_expr!default_expr,
比如 ${mouse!"No mouse."} 當mouse不存在時,返回default value;
(product.color)!"red" 這種方式,能夠處理product或者color為miss value的情況;
而product.color!"red"將只處理color為miss value的情況
?? : Missing value test operator ,測試是否為missing value
unsafe_expr?? :product.color??將只測試color是否為null
(unsafe_expr)??:(product.color)??將測試product和color是否存在null
--------------------------------------------------------------------------------------------------------------------------------------------------
以下引用官方描述:
引用
The FreeMarker template language doesn't know the Java language null at all. It doesn't have null keyword, and it can't test if something is null or not.
1.判斷是否存在,通過exists關鍵字或者"??"運算子。都將返回一個布林值
user.name?exists
user.name??
-
<#if user.name?exists>
-
//TO DO
-
</#if>
-
<#if user.age??>
-
//TO DO
-
</#if>
2.忽略null值
假設前提:user.name為null
${user.name},異常
${user.name!},顯示空白
${user.name!'vakin'},若user.name不為空則顯示本身的值,否則顯示vakin
${user.name?default('vakin')},同上
${user.name???string(user.name,'vakin')},同上
! :default value operator,語法結構為:unsafe_expr!default_expr,
比如 ${mouse!"No mouse."} 當mouse不存在時,返回default value;
(product.color)!"red" 這種方式,能夠處理product或者color為miss value的情況;
而product.color!"red"將只處理color為miss value的情況
?? : Missing value test operator ,測試是否為missing value
unsafe_expr?? :product.color??將只測試color是否為null
(unsafe_expr)??:(product.color)??將測試product和color是否存在null
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
freemarker中的null異常處理以及!與??的使用 2
如工程包含:
在user中我們有個角色,那麼我們可以通過${user.role.rolename}獲取當前使用者的角色名稱
問題來了當role沒有賦值的時候,在jsp中${}表示式會直接忽略不顯示,而freemarker會報異常,還是一大堆,freemarker就需要您手動去處理
如:
這的role是null因此報錯了,而在freemarker中報的異常,排錯還挺難的,一大頓,這裡就需要我們手動去處理null,這裡就要用到!
此刻的效果就跟jsp中的${}el表示式一樣了,如果為空就不顯示了,當在!後進行說明如:獲取當前使用者的角色:${user.role!"當前使用者沒有角色"}如果為空預設值就是後面的值
而當您寫成這樣的時候:<br/>獲取當前使用者的角色:${user.role.rolename!} 而role任然沒值的時候依然會報錯,而正確的方式<br/>獲取當前使用者的角色:${(user.role.rolename)!}
?? 用於判斷是否為空
<#if user.role??>
當前使用者沒有許可權角色
<#else>
當前使用者有許可權角色
</#if>
${user.role???string}這裡將結果以字串的形式輸出:true 或者false
${user.role???string("YES","NO")} 這判定使用者許可權角色為空