Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The wrap and anchor options are implemented via the Output Filters. The others are handled during interpretation by ST. Well, the filters also are notified that a separator vs regular string is coming out to prevent newlines between real elements and separators.

...

Java examples

Here is an example use of the format option.

...

Code Block
public void testRendererWithFormatAndSeparatorAndNull() throws Exception {
    StringTemplate st =new StringTemplate(
        "The names: <names; separator=\" and \", null=\"n/a\", format=\"upper\">",
        AngleBracketTemplateLexer.class);
    List names = new ArrayList();
    names.add("ter");
    names.add(null);
    names.add("sriram");
    st.setAttribute("names", names);
    st.registerRenderer(String.class, new StringRenderer());
    String expecting = "The names: TER and N/A and SRIRAM";
    String result = st.toString();
    assertEquals(expecting, result);
}

Python examples

If you are constructing HTML documents you have to escape plain text strings so that < or & characters appear as literal text and do not act as HTML delimiters (thus opening a wide range of possible attacks if the text originated from user input).

Code Block

import cgi
import stringtemplate3

group = stringtemplate3.StringTemplateGroup(
    name="default", rootDir="path/to/templates/"
    )

class EscapeRenderer(stringtemplate3.AttributeRenderer):
    def toString(self, o, formatName=None):
        if formatName is None:
            # no formatting specified
            return str(o)

        if formatName == "escape":
            return cgi.escape(str(o))
        else:
            raise ValueError("Unsupported format name")

group.registerRenderer(str, EscapeRenderer())

st = group.getInstanceOf("blogEntry")
st['comment'] = database.loadComment() # an instance with username, text, url, ... attributes

Then you can use $comment.text; format="escape"$ in your templates whenever an attribute is not known to be save.