1. 程式人生 > >Freemarker判斷序列中是否包含某個元素

Freemarker判斷序列中是否包含某個元素

在Freemarker中,如果要判斷序列中是否包含某個指定的元素,可以使用freemarker的內建函式seq_contains。

注:seq_contains這個內建函式從FreeMarker 2.3.1 版本開始可用。而在2.3 版本中不存在

使用示例:

<#--宣告一個序列,包含若干個元素-->  
<#assign x = ["red", 16, "blue", "cyan"]>  
<#--使用seq_contains判斷序列中的元素是否存在-->  
"blue": ${x?seq_contains("blue")?string("yes", "no")}  
"yellow": ${x?seq_contains("yellow")?string("yes", "no")}  
16: ${x?seq_contains(16)?string("yes", "no")}  
"16": ${x?seq_contains("16")?string("yes", "no")}  

輸出結果:

Freemarker程式碼

"blue": yes  
"yellow": no  
16: yes  
"16": no  

附:seq_字首在這個內建函式中是需要的,用來和contains 區分開。contains函式用來在字串中查詢子串(因為變數可以同時當作字串和序列)。