Renderers

Skip to end of metadata
Go to start of metadata

 

The atomic element of a template is a simple attribute (object) that is rendered to text by its the appropriate string evaluation method for the port's language (toString, ToString, _str_, ...). For example, an integer object is converted to text as a sequence of characters representing the numeric value . What if we want commas to separate the 1000's places like 1,000,000? What if we want commas and sometimes periods depending on the locale? For more, see The Internationalization and Localization of Web Applications.

StringTemplate lets you register objects that know how to format or otherwise render attributes to text appropriately. There is one registered renderer per type per group. In the statically defined port languages like Java and C#, we use an interface to describe these renderers:

 

 

To render expression <e>, StringTemplate looks for a renderer associated with the object type of e, say, t. If t is associated with a registered renderer, r, it is suitable and StringTemplate invokes the renderer method

 

In Java:

Expression syntax

How interpreter invokes renderer r

<e>

r.toString(e, null, locale)

<e; format="f">

r.toString(e, "f", locale)

 

In C#:

Expression syntax

How interpreter invokes renderer r

<e>

r.ToString(e, null, locale)

<e; format="f">

r.ToString(e, "f", locale)

 

StringTemplate supplies either the default locale, or whatever locale was set by the programmer. If the format string passed to the renderer is not recognized then the renderer should simply call the usual string evaluation method.

To register a renderer, we tell the group to associate an object type with a renderer object. Here's an example that tells StringTemplate to render numbers with an instance of NumberRenderer using the Polish locale:

 


StringTemplate matches the types of expressions with the renderers using the "is instance of" relationship. As in this example, we registered a renderer for numbers and StringTemplate used it for subclasses such as integers and floating-point numbers. Here's the renderer definition:

 

 

StringTemplate comes with three predefined renderers: DateRenderer, StringRenderer, and NumberRenderer.

Labels:
  1. Nov 30, 2011

    Is it possible to use another template to specify the format string?

    Ok, I answered myself: you can do  <y; format=(template)>