Search code examples
javaliststringtemplate

Java StringTemplate Iterating over List of Complex Object


I have a class like so:

public class Foo {
    private String s;
}

And I have a list of said objects. I want to be able to iterate over this list and print out the string property s. I have the following code to render the string template:

Map<String, Object> params = new HashMap<>();
List<Foo> foos = new ArrayList<>();
foos.add(new Foo("A"));
foos.add(new Foo("B"));
foos.add(new Foo("C"));
params.put("foos", foos);
ST st = new ST("Hello, $data.(\"foos\") : {foo | $foo.s;separator=\", \"$}$", '$', '$');
st.add("data", params);
template = st.render();
System.out.println(template);

But the output is just:

Hello, ABC

How do I properly iterate over that list and print it out with comma separation?


Solution

  • Your separator separates the elemnets of foo.s, not those of foo. Try

    ST st = new ST("Hello, $data.(\"foos\") : {foo | $foo.s$};separator=\", \"$", '$', '$');