[stringtemplate-interest] new renderers: String and Number

Terence Parr parrt at cs.usfca.edu
Fri Nov 13 18:41:59 PST 2009


Hiya.  I'm sending new renderers in case you want for v3.  I'm including locale now in rendering.  I still call toString on any object w/o a renderer though.  These renderers pass format strings to java's printf like thing. E.g.,

    @Test public void testLocaleWithNumberRenderer() throws Exception {
        String templates =
                "foo(x,y) ::= << <x; format=\"%,d\"> <y; format=\"%,2.3f\"> >>\n";

        writeFile(tmpdir, "t.stg", templates);
        STGroup group = new STGroupFile(tmpdir+"/t.stg");
        group.registerRenderer(Integer.class, new NumberRenderer());
        group.registerRenderer(Double.class, new NumberRenderer());
        ST st = group.getInstanceOf("foo");
        st.add("x", -2100);
        st.add("y", 3.14159);
        // Polish uses ' ' for ',' and ',' for '.'
        String expecting = " -2 100 3,142 ";
        String result = st.render(new Locale("pl"));
        assertEquals(expecting, result);
    }

Here are the renderers (note only 1 method in renderer in v4).

import java.util.*;

/** Works with Byte, Short, Integer, Long, and BigInteger as well as
 *  Float, Double, and BigDecimal.  You pass in a format string suitable
 *  for Formatter object:
 *
 *  http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html
 *
 *  Can even do longs to date conversions.
 */
public class NumberRenderer implements AttributeRenderer {
    public String toString(Object o, String formatString, Locale locale) {
        // o will be instanceof Number
        if ( formatString==null ) return o.toString();
        Formatter f = new Formatter(locale);
        f.format(formatString, o);
        return f.toString();
    }
}

import java.util.*;

public class StringRenderer implements AttributeRenderer {
    // trim(s) and strlen(s) built-in funcs; these are format options
    public String toString(Object o, String formatString, Locale locale) {
        String s = (String)o;
        if ( formatString==null ) return s; 
        if ( formatString.equals("upper") ) return s.toUpperCase(locale);
        if ( formatString.equals("lower") ) return s.toLowerCase(locale);
        if ( formatString.equals("cap") ) {
            return Character.toUpperCase(s.charAt(0))+s.substring(1);
        }
        if ( formatString.equals("url-encode") ) {
            return s; // TODO: impl
        }
        if ( formatString.equals("xml-encode") ) {
            return s; // TODO: impl
        }
        return String.format(formatString, s);
    }
}



More information about the stringtemplate-interest mailing list