stringtemplatestringtemplate-4

Stringtemplate - use conditionals without adding newlines to the output, and still keep templates legible?


I have something like this:

properties(attributeInfo) ::= <<
private <attributeInfo:parameters()>;

>>

parameters(attributeInfo) ::= <<
<if(attributeInfo.struct||attributeInfo.array)><attributeInfo:paramComposite()><else><javaTypeNameMap.(attributeInfo.typeName)> <attributeInfo.propertyName><endif>
>>

This produces the desired output:

private com.terradatum.common.db.model.terradatum.MlsAgentIdObj agentObj;
private String officeName;
private String officeAddress;
private String officeCity;
private String officeState;
private String officeZipcode;
private MlsPhoneTbl phoneTbl;
private String agentEmail;
private String agentAddress;
private String agentCity;
private String agentState;
private String agentZipcode;

When I change the parameters subtemplate to the following:

parameters(attributeInfo) ::= <<
<if(attributeInfo.struct||attributeInfo.array)><attributeInfo:paramComposite()>
<else><javaTypeNameMap.(attributeInfo.typeName)> <attributeInfo.propertyName>
<endif>
>>

The template is more legible, but the output now includes newlines:

private com.terradatum.common.db.model.terradatum.MlsAgentIdObj agentObj
;
private String officeName
;
private String officeAddress
;
private String officeCity
;
private String officeState
;
private String officeZipcode
;
private MlsPhoneTbl phoneTbl
;
private String agentEmail
;
private String agentAddress
;
private String agentCity
;
private String agentState
;
private String agentZipcode
;

I'm confused by this behavior - based on what I understood about how to conditionally include subtemplates, and the behavior of conditionals WRT to newlines, the two forms of the parameters subtemplate should produce the same output.

Clearly my understanding is incorrect, so I'm hoping someone will give me some guidance.


Solution

  • Try:

    parameters(attributeInfo) ::= <%
    <if(attributeInfo.struct||attributeInfo.array>
      <attributeInfo:paramComposite()>
    <else><javaTypeNameMap.(attributeInfo.typeName)>
      <attributeInfo.propertyName>
    <endif>
    %>
    

    <% ...%> lets stringtemplate ignore separating white space. << ...>> only ignores leading and trailing newlines.

    In some case also the call of the function trim could help.