I'm trying to call a Java method in my FreeMarker template that uses a public static Java variable as one of its parameters. For example, if the FreeMarker code in a test.ftl is this:
${javaClass.getSomething(javaClass.VARIABLE)}
and if the class JavaClass looks like this:
public class JavaClass {
public static final int VARIABLE = 1;
public String getSomething(int var) {
...
}
I receive errors when using the template that look like this:
[echo] Expression JavaClass is undefined on line 40, column 81 in com/test/template/path/test.ftl.
[echo] The problematic instruction:
[echo] ----------
[echo] 03:53:01,146 ERROR [main][runtime:96] Template processing error: "Expression JavaClass is undefined on line 40, column 81 in com/test/template/path/test.ftl"
[echo]
[echo] ==> ${javaClass.getSomething(javaClass.VARIABLE)} [on line 40, column 25 in com/test/template/path/test.ftl] Expression JavaClass is undefined on line 40, column 81 in com/test/template/path/test.ftl.
[echo]
[echo] ----------The problematic instruction:
[echo]
[echo]
[echo] ----------
[echo] Java backtrace for programmers:
[echo] ----------
[echo] ==> ${javaClass.getSomething(javaClass.VARIABLE)} [on line 40, column 25 in com/test/template/path/test.ftl]freemarker.core.InvalidRe
ferenceException: Expression JavaClass is undefined on line 40, column 81 in com/test/template/path/test.ftl.
...
...
This error is complaining that it doesn't like the javaClass.VARIABLE and throws the InvalidReferenceException. I've tried specifying this in other different ways, such as JavaClass.VARIABLE, ${javaClass.VARIABLE}, and ${JavaClass.VARIABLE}, but they all throw errors.
How would you call a public Java variable from within a Java method in a FreeMarker (.ftl) template?
Freemarker's data model doesn't map static fields on objects passed in automatically, so you'd have to use a beanwrapper http://freemarker.org/docs/pgui_misc_beanwrapper.html.
import freemarker.ext.beans.BeansWrapper;
BeansWrapper w = new BeansWrapper();
TemplateHashModel statics = w.getStaticModels();
model.addAttribute("myVariable", statics);
then in your template, use
${myVariable["fully.qualified.package.ClassName"].FIELD_NAME}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With