有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我试图在我的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) 个答案

  1. # 1 楼答案

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