Data Models

Multiple Models

More than one template model can be implemented at a time for a given class. For instance, a class could have the following signature:

public class MyModel implements TemplateHashModel, TemplateMethodModel,
        TemplateListModel2 {

    // Implementation goes here...


}

When presented with a class such as the above, FM-Classic will attempt to "do the right thing". Supposing such a class was placed inside a TemplateModelRoot implementation, under the key name of demo. A FM-Classic template could perform all of the following:

<comment>
The following will index element one of the TemplateListModel 
implementation...
</comment>

The second element of the list is: ${demo[ 1 ]}

<comment>
The following will reference the key name "hello" of the TemplateHashModel 
implementation...
</comment>

Say hello: ${demo.hello}
And again: ${demo[ "hello" ]}

<comment>
The following will call the "demo" method (the TemplateMethodModel
implementation)...
</comment>

Call from the demo() method... ${demo()}

Caveats

Special care needs to be takes when implementing TemplateListModel and TemplateHashModel within the same class. In practise, this means avoiding having numeric keys inside a TemplateHashModel.

If you use dot notation (eg. foo.bar) to reference keys inside your model, FM-Classic will always treat the key as being a TemplateHashModel.

If you use dynamic key notation (eg. foo[ bar ]), FM-Classic will first check whether the key can be evaluated as a numeric value, such as a TemplateNumberModel. If it can, it will use the TemplateListModel or TemplateListModel2 implementation. If the key can only be evaluated as a String value, it will then fall-back on looking up the key using the TemplateHashModel.