Methods

Method variables exposed to a template implement the TemplateMethodModel interface. This contains one method: TemplateModel exec(java.util.List arguments). When you call a method with a method call expression, then the exec method will be called. The arguments parameter will contain the values of the FTL method call arguments. The return value of exec gives the value of the FTL method call expression.

The TemplateMethodModelEx interface extends TemplateMethodModel. It does not add any new methods. The fact that the object implements this marker interface indicates to the FTL engine that the arguments should be put to the java.util.List directly as TemplateModel-s. Otherwise they will be put to the list as String-s.

For obvious reasons there is no default implementation for these interfaces.

Example: This is a method, which returns the index within the second string of the first occurrence of the first string, or -1 if the second string doesn't contains the first.

public class IndexOfMethod implements TemplateMethodModel {
    
    public TemplateModel exec(List args) throws TemplateModelException {
        if (args.size() != 2) {
            throw new TemplateModelException("Wrong arguments");
        }
        return new SimpleNumber(
            ((String) args.get(1)).indexOf((String) args.get(0)));
    }
}  

If you put an instance of this, say, into the root:

root.put("indexOf", new IndexOfMethod());  

then you can call it in the template:

<#assign x = "something">
${indexOf("met", x)}
${indexOf("foo", x)}  

and then the output will be:

2
-1  

If you need to access the runtime FTL environment (read/write variables, get the current locale, etc.), you can get it with Environment.getCurrentEnvironment().

FreeMarker Manual -- For FreeMarker 2.3.20
HTML generated: 2013-06-27 20:54:33 GMT
Edited with XMLMind XML Editor
Here!