StringTemplate 缩进在 String 内添加空格

2024-02-25

这显然是一个SSCCE。

我有以下模板文件:

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

...使用以下代码:

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());
}

该代码产生:

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

换句话说,字符串值会随着空格的添加而被修改。当客户端解析 XML 文件时,即使进行了空格修剪,字符串值也会被视为已更改,因为添加了空格inside字符串。

我知道解决方案是将模板声明为:

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

...但即使这个解决方案也需要所有其他可能包含xml渲染也是右对齐的。

例如,假设上面渲染的值嵌入到另一个模板中,则以下模板:

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

...还必须重写为:

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

...实际上需要确定所有节点的左对齐。

有没有办法指示 StringTemplate 按原样发出特定的 String 参数(如果其中存在新行,则不缩进),同时保留所有其他情况下的空格/缩进(以便我的渲染输出不会长得丑)?

Update

我尝试使用无缩进写入器 http://www.stringtemplate.org/api/index.html?org/stringtemplate/v4/NoIndentWriter.html却被遇见了有其他问题 https://stackoverflow.com/q/27931007/274677。所以看来NoIndentWriter确实按原样发出多行字符串,但确实如此not尊重模板文件中存在的空白。所以我又回到了第一方。


所以最后我所做的是使用无缩进写入器 http://www.stringtemplate.org/api/index.html?org/stringtemplate/v4/NoIndentWriter.html用给定的代码在这篇文章中 https://stackoverflow.com/q/27931007/274677。然后,为了解决缺少缩进导致 XML 丑陋的问题(在上述帖子中抱怨过),我使用了描述的 XML 漂亮打印机here https://stackoverflow.com/a/11519668/274677.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

StringTemplate 缩进在 String 内添加空格 的相关文章

随机推荐