如何检查使用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==" part "等属性值。如果你不要设置属性或传递空值属性,即属性的计算结果为false。StringTemplate也返回false空列表和映射以及"空"迭代器,如0-length列表(参见interpreter . testatattributetrue())。所有其他属性除布尔对象外,求值为true。布尔对象计算为其对象值。严格来说,这是违反了分离,但是布尔值为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: