如何在FreeMarker中调用公共Java变量

时间:2015-02-07 13:37:35

标签: java freemarker

我正在尝试在FreeMarker模板中调用Java方法,该模板使用公共静态Java变量作为其参数之一。例如,如果test.ftl中的FreeMarker代码是:

${javaClass.getSomething(javaClass.VARIABLE)}

如果班级JavaClass看起来像这样:

public class JavaClass {

    public static final int VARIABLE = 1;

    public String getSomething(int var) {
    ...
    }

使用如下所示的模板时收到错误:

[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. ... ...

此错误表示它不喜欢javaClass.VARIABLE并抛出InvalidReferenceException。我尝试以其他不同的方式指定此内容,例如JavaClass.VARIABLE${javaClass.VARIABLE}${JavaClass.VARIABLE},但它们都会抛出错误。

如何从FreeMarker(.ftl)模板中的Java方法中调用公共Java变量?

1 个答案:

答案 0 :(得分:3)

Freemarker的数据模型不会映射自动传入的对象上的静态字段,因此您必须使用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);

然后在您的模板中,使用

${myVariable["fully.qualified.package.ClassName"].FIELD_NAME}