[stringtemplate-interest] joining attributes with a separator when some are optional
Henno Vermeulen
henno at huizemolenaar.nl
Tue May 29 06:54:20 PDT 2012
There is a problem in my unit test, the last ", vanDerWaals" should be replaced by ".render()".
I found that "<[firstName, surNamePrefix, surName]; separator=\" \">" seems to work well, however with errors printed to the console for my unit test because they are missing. This can be solved by explicitly setting these to null. So when working with a Person JavaBean we could do something like the following. Unfortunately we still need to explicitly pass nulls instead of empty strings. Perhaps I can create a subtemplate for this and as a bonus also make the separator a parameter of the subtemplate to clean up the syntax a bit.
static class Person {
public String firstName;
public String surNamePrefix;
public String surName;
public Person(String firstName, String surNameSurNamePrefix,
String surName) {
this.firstName = firstName;
this.surNamePrefix = surNameSurNamePrefix;
this.surName = surName;
}
}
@Test
public void personFirstNamePrefixSurNameJoinedNonEmpty() {
String personTemplate =
"<[person.firstName, person.surNamePrefix, person.surName]; separator=\" \">";
assertEquals(
"Max Planck",
new ST(personTemplate).add("person",
new Person("Max", null, "Planck")).render());
assertEquals(
"Einstein",
new ST(personTemplate).add("person",
new Person(null, null, "Einstein")).render());
assertEquals(
"Albert",
new ST(personTemplate).add("person",
new Person("Albert", null, null)).render());
assertEquals(
"Johannes Diderik van der Waals",
new ST(personTemplate).add("person",
new Person("Johannes Diderik", "van der", "Waals"))
.render());
}
Henno
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/stringtemplate-interest/attachments/20120529/0a2e2031/attachment-0001.html
More information about the stringtemplate-interest
mailing list