Scalars

Each node in the data model tree must implement one of the subinterfaces of TemplateModel. The root node must implement TemplateModelRoot. The other nodes must implement TemplateHashModel, TemplateSequenceModel, TemplateCollectionModel, TemplateScalarModel, TemplateNumberModel, TemplateMethodModel, or TemplateMethodModelEx.

Scalars are the most simple of the TemplateModels. A scalar model simply returns a single value as a String.

The one method that TemplateScalarModel declares is:

public java.lang.String getAsString(java.util.Locale l)
                             throws TemplateModelException;
        

Note that, as of Freemarker 2.0 final, the above method takes a Locale as a parameter. The SimpleScalar implementation does not use this parameter, though the SimpleNumber does, currently to get the locale's decimal separator. Customized versions of this interface may or may not use the parameter, depending on whether the value needs to be localized.

All of the TemplateModels can throw TemplateModelExceptions. Normally when a TemplateModelException is thrown, FreeMarker will embed the error message in the output, inside an HTML comment.

All TemplateModels also declare the isEmpty() method. If the TemplateModel is empty, for instance, when a list contains no values, or a scalar has no value, this method should return false. This is used primarily for FreeMarker to check for boolean values.

If for some reason you need to return a boolean "false" value or an empty string, getAsString() can safely return a null value.

Numbers

In version 2.0, we have a new subinterface of TemplateScalarModel, TemplateNumberModel, which is used when we want to treat the scalar in question as a numerical value. It defines an extra method:

public java.lang.Number getAsNumber()
                             throws TemplateModelException;
        

All numbers that are specified as literals in the template, or are a result of arithmetic calculations in the template will be internally represented as instances of the Java's built in arbitrary-precision arithmetic class, java.math.BigDecimal. While this provides for arbitrary-precision arithmetic in the templates, it can sometime create unusual results. If you want to explicitly force the internal representation of these numbers to some other type, you can use the syntax numericExpression?type where type can be a name of any primitive Java number type (byte, short, int, long, float, double) as well as string for converting the number into string. This feature is handy (among other purposes) for specifying the exact numeric type of arguments to reflected invocations of overloaded methods (see "Models For Arbitrary Java Models" on details on how to make these) like in obj.someMethod(1?int), as well as for rounding of fractions like in (a / b)?long.