Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringTemplate check if array is empty in java

How to check using the StringTemplate if the array is not empty?

The example below doesn't work:

<if(teams.length > 0)>
  <ul>
    <teams:{team | <li><team></li> }>
  </ul>
<endif>

Other (not working) Exaple:

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());

Output:

list: 123, 124
--------
list: 
like image 329
czerasz Avatar asked Apr 25 '26 01:04

czerasz


1 Answers

Just use:

<if(teams)>

This condition will evaluate to false if the teams list is empty. From the StringTemplate documentation:

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.

Example:

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());

Output:

1: list: 123, 124
--------
2: 
like image 151
Sionnach733 Avatar answered Apr 27 '26 13:04

Sionnach733