Magnolia 5.3 reached end of life on June 30, 2017. This branch is no longer supported, see End-of-life policy.
Template model is a Java object that contains template logic. We recommend that you put templating logic in the model rather than trying to do too much in a template script. A template renderer executes the model before it calls the template script. The model can retrieve data, perform a calculation or do anything the template needs. The result of the model's execute()
method is passed to the template script with an actionResult
object. The model can also act as a bean for getting or setting POST
or GET
parameters if the class provides the corresponding getter and setter functions.
In Freemarker you can access any public function of the associated model class with the model
object. Eg:
public String getName()
${model.getName()}
${model.name}
public boolean isArchived()
${model.isArchived()}
[#if model.archived!false] ... [/#if]
public String getAddress(String user)
${model.getAddress("John Smith")}
TODO: JSP example
The following Java objects are always passed to a model class (TODO: from where, why):
It is also recommended to make use of Java Generics (TODO: Link yes or no? Different link?) to ensure type safety. This avoids run time errors in case the type is being cast wrong, since it would already throw an error at compile time and could be fixed pre-production. Furthermore wildcards ( <?>
) and upper bounds for wildcards ( <? extends Number>
) can be used.
public class MyCustomModel<RD extends ConfiguredTemplateDefinition> extends RenderingModelImpl<ConfiguredTemplateDefinition> { public MyCustomModel(Node content, ConfiguredTemplateDefinition definition, RenderingModel<?> parent) { super(content, definition, parent); } }
There are many advantages of using a model class. For example, the business logic can be exchanged while the script output remains the same. The same model class can also be reused for different templates so the code does not need to be duplicated. Since there is a clean separation between logic and output, these two can be developed independently by different developers (java vs. frontend developer). Another advantage, that is not neglectable, is the protection of your code. While it is possible to change the output of templates with the inplace templating module, you cannot change the business logic without restart of the server and without access to the source code. This applies to model classes programmed in Java, you can change the code in a running instance if you are using Groovy model classes however.