gpt4 book ai didi

java - StringTemplate 检查数组在 java 中是否为空

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:47:18 25 4
gpt4 key购买 nike

如果数组不为空,如何使用 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文档:

The conditional expressions test of the presence or absence of an attribute. Strict separation of model and view requires that expressions cannot test attribute values such as name=="parrt". If you do not set an attribute or pass in a null-valued attribute, that attribute evaluates to false. StringTemplate also returns false for empty lists and maps as well a "empty" iterators such as 0-length lists (see Interpreter.testAttributeTrue()). All other attributes evaluate to true with the exception of Boolean objects. Boolean objects evaluate to their object value. Strictly speaking, this is a violation of separation, but it's just too weird to have Boolean false objects evaluate to true just because they are non-null.

例子:

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:

关于java - StringTemplate 检查数组在 java 中是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22718587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com