[英]StringTemplate check if array is empty in java
如果數組不為空,如何使用 StringTemplate 進行檢查?
下面的例子不起作用:
<if(teams.length > 0)>
<ul>
<teams:{team | <li><team></li> }>
</ul>
<endif>
其他(不工作)示例:
String content = "<if(teams)>list: <teams;separator=\", \"><endif>";
ST template = new ST(content);
template.add("teams", new Long[]{123L, 124L});
System.out.println(template.render());
System.out.println("--------");
content = "<if(teams)>list: <teams;separator=\", \"><endif>";
template = new ST(content);
template.add("teams", new Long[]{});
System.out.println(template.render());
輸出:
list: 123, 124
--------
list:
只需使用:
<if(teams)>
如果teams
列表為空,則此條件將評估為 false。 從StringTemplate文檔:
條件表達式測試屬性是否存在。 模型和視圖的嚴格分離要求表達式不能測試 name=="parrt" 等屬性值。 如果未設置屬性或傳入空值屬性,則該屬性的計算結果為 false。 StringTemplate 還為空列表和映射以及“空”迭代器(例如 0 長度列表)返回 false(請參閱 Interpreter.testAttributeTrue())。 除布爾對象外,所有其他屬性的計算結果均為真。 布爾對象計算其對象值。 嚴格來說,這違反了分離,但僅僅因為它們是非 null 就讓 Boolean false 對象評估為 true 實在是太奇怪了。
例子:
String content = "1: <if(teams)>list: <teams;separator=\", \"><endif>";
ST template = new ST(content);
// Create a list with two items
List<Long> teams = new ArrayList<Long>();
teams.add(123L);
teams.add(124L);
template.add("teams", teams);
System.out.println(template.render());
// Add separator
System.out.println("--------");
content = "2: <if(teams)>list: <teams;separator=\", \"><endif>";
template = new ST(content);
// Create empty list
teams = new ArrayList<Long>();
template.add("teams", teams);
System.out.println(template.render());
輸出:
1: list: 123, 124
--------
2:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.