2015-02-07 70 views
2

我試圖在我的FreeMarker模板中調用Java方法,該方法使用公共靜態Java變量作爲其參數之一。例如,如果在test.ftl FreeMarker的代碼是這樣的:如何在FreeMarker中調用公共Java變量

${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和thro是InvalidReferenceException。我試過用其他不同的方式來指定它,例如JavaClass.VARIABLE,${javaClass.VARIABLE}${JavaClass.VARIABLE},但它們都會引發錯誤。

如何從FreeMarker(.ftl)模板中的Java方法中調用公共Java變量?

回答

2

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} 
+0

這是更好地使用在'Configuration'使用'ObjectWrapper',假設它是一個'BeansWrapper'子類(如'DefaultObjectWrapper')。 – ddekany 2015-02-08 17:45:53

+1

此外,它可能更好做'model.addAttribute(「ClassName」,statics.get(ClassName.class.getName()))',所以然後在模板中,你可以簡單地寫'$ {ClassName.FIELD_NAME}'。 – ddekany 2015-02-08 17:49:19

+0

是的,公平 - 製作關鍵的類名,然後單獨爲該類添加模型可能更好。 – Chii 2015-02-10 05:58:30