[stringtemplate-interest] joining attributes with a separator when some are optional
Henno Vermeulen
henno at huizemolenaar.nl
Tue May 29 05:51:15 PDT 2012
Hello,
What would be the simplest syntax with StringTemplate to join multiple attributes with a separator without getting too many separators when an attribute is empty/absent/null? This is a use case I encounter very often! I normally solve it in Java using a utility method "joinNonBlank(separator, String... strings)" which only concats the non-blank Strings with the given separator.
For example when formatting a person's name or address and certain attributes (e.g. surname prefix, country of address) are optional.
A complete address could be formatted as "<address>\n<zipCode> <city>\n<country>". However, I don't want the separating "\n" in case the country is absent and I don't want the space between zipCode and city if either of them are absent. Similarly a person's name may be formatted as "<firstName> <surNamePrefix> <surName>", but I don't want a separating space in case a field is empty/absent/null.
Below you can find a failing unit test (because of extra spaces) where I would like the personTemplate changed so that it satisfies the test. (Will the solution make a difference if the attributes are part of a Person object as in "<person.firstName> < person.surNamePrefix> < person.surName>"?)
Thank you,
Henno Vermeulen
Huize Molenaar
@Test
public void firstNamePrefixSurNameJoinedNonEmpty() {
// TODO how do we join multiple attributes with a separator?
String personTemplate = "<firstName> <surNamePrefix> <surName>";
assertEquals(
"Max Planck",
new ST(personTemplate).add("firstName", "Max")
.add("surName", "Planck").render());
assertEquals("Einstein",
new ST(personTemplate).add("surName", "Einstein").render());
assertEquals("Albert", new ST(personTemplate)
.add("firstName", "Albert").render());
assertEquals("Johannes Diderik van der Waals",
new ST(personTemplate).add("firstName", "Johannes Diderik")
.add("surNamePrefix", "van der")
.add("surName", "Waals"), vanDerWaals);
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/stringtemplate-interest/attachments/20120529/99207030/attachment.html
More information about the stringtemplate-interest
mailing list