[stringtemplate-interest] Problem with fixed-length custom object renderer
Frédéric Delanoy
frederic.delanoy at gmail.com
Thu Feb 26 02:44:20 PST 2009
Hi All,
I'm trying to implement a custom object renderer to ouput fixed-length
data. I set an attribute to a list
of strings, and output it using a newline separator.
However, only the first line is correctly indented
Here's what I used:
public class TestStringTemplate_FixedLength {
/** Renders a string by appending with spaces to get a minimal size */
public static class FixesLengthRenderer implements AttributeRenderer {
private final int length;
public FixesLengthRenderer(int length) {
this.length = length;
}
/** returns a char[] composed of n copies of character c, or
empty string if n < 1 */
private char[] times(int n, char c) {
if (n < 1) return new char[0];
char[] cc = new char[n];
for (int i = 0; i < cc.length; i++) cc[i] = c;
return cc;
}
/** Returns a copy of s of size n; string value is truncated
or white-space-appended if needed */
private String adaptStringToSize(String s, int size) {
if (size < 1) return "";
int len = s.length();
StringBuilder sb = new StringBuilder(size);
sb.append(s.substring(0, Math.min(len, size)));
sb.append(times(size - len, ' '));
return sb.toString();
}
public String toString(Object o) { return
adaptStringToSize((String) o, length); }
public String toString(Object o, String formatName) { return
toString(o); }
}
public static void main(String[] args) {
StringTemplate st= new StringTemplate("$elems:{$it$ foo};
separator=\"\n\"$");
st.registerRenderer(String.class, new FixesLengthRenderer(6));
st.setAttribute("elems", new String[] { "ABC", "DEFG" });
System.out.println(st.toString());
}
}
The output I have is:
ABC foo
DEFG foo
Can s.o. please help?
Thanks in advance,
Frédéric Delanoy
More information about the stringtemplate-interest
mailing list