String indentation StringTemplate adds space inside String

This is obviously SSCCE.

I have the following template file:

xml(value)::=<<
<a>
    <b>
        ^value^
    </b>
</a>
>>

      

... with the following code:

private static final String VALUE="alpha\nbeta";
public static void main(String args[]) throws Exception {
    STGroup stGroup = new STGroupFile("templates/a.xml.stg", '^', '^');
    ST st = stGroup.getInstanceOf("xml");
    st.add("value", VALUE);
    System.out.printf("--------\n%s\n--------", st.render());
}

      

The code creates:

 [java] --------
 [java] <a>
 [java]     <b>
 [java]         alpha
 [java]         beta
 [java]     </b>
 [java] </a>
 [java] --------

      

In other words, the String value changes when spaces are added. When the client parses the XML file, even if the whitespace is trimmed, the String value will be treated as modified because the whitespace has a string added inside .

I understand that the solution is to declare the template as:

xml(value)::=<<
<a>
    <b>^value^</b>
</a>
>>

      

... but even this solution requires that all other nodes that may contain rendering xml

are also properly justified.

For example, assuming the above value is embedded in another template, then the following template:

enclosing-document(xml)::=<<
<h1>
    <h2>
        ^xml^
    </h2>
</h1>
>>

      

... would also need to be rewritten as:

enclosing-document(xml)::=<<
<h1>
    <h2>
^xml^
    </h2>
</h1>
>>

      

... essentially, which requires all nodes to be left-aligned.

Is there a way to instruct the StringTemplate to just fix the specific String parameter as it is (not backing away from it in case new lines appear inside), while still preserving whitespace / indentation for all other cases (so my rendering output won't be ugly)?

Update

I tried using NoIndentWriter , but was met with other issues , So it seems to NoIndentWriter

actually emit a multiline string as it is, but has no whitespace honor present in the template file. So I went back to the fore.

+3


source to share


1 answer


So in the end what I did was to use the NoIndentWriter with the code in this post . Then, to resolve the lack of indentation that results in ugly XML (complained in the above post), I used the XML printer described here .



0


source







All Articles