Hash models are probably the most common model you'll use in FreeMarker.
Like TemplateScalarModel, TemplateHashModel
defines only one method:
public TemplateModel get(java.lang.String key)
throws TemplateModelException;
FreeMarker uses this method to return a value for a given key name. This
method is equivalent to the get() method in the Java 2
java.util.Map interface.
If the specified key does not exist in the hash, the results are
implementation dependant. Some people may throw a
TemplateModelException, others might return null,
still others might return a default value. All are considered to be
valid in FreeMarker.
Similarly, if the get() method is passed a null
value, which can happen when a hash is indexed by another FreeMarker variable,
the results are undefined. The implementing class may be expected to
throw a TemplateModelException, or otherwise gracefully
deal with the null value.
Hash models are powerful because humans tend to recognise things in terms of names rather than numbers. Hash models can return other models. A hash model can contain other hash models, and so on (as we saw in the introduction).
Key names should not include any dots (".") as part of the name. This is
because FreeMarker uses the dot character to determine when a key name
is complete, and to then traverse into the next TemplateModel. If you're
tempted to use a dot in your key name, try a different separator instead, or
make sure you always use the Dynamic Key Name operator (the []
operator).
Similarly, key names beginning with a number are also discouraged.
FreeMarker uses the first character to help determine whether a dynamic key
is referencing a TemplateListModel or a
TemplateHashModel.
Finally, key names beginning with an underscore ("_") should be avoided. These may be used as special keys by future versions of FreeMarker.
| Previous: List Models | Next: Model Roots |