简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM