如何在FTL中访问普通的java对象?

时间:2015-04-23 09:04:34

标签: spring-mvc freemarker

我正在使用带有Freemarker模板的Spring 4。我有一个帮助器类,我想在我的FTL模板文件中访问它的方法。我不想将它作为模型传递。我该怎么办?

2 个答案:

答案 0 :(得分:1)

看看这个,它可以帮助你传递助手类:{{3}}

    int N = 20000;
    std::string alphabet("ACGT");
    std::string str;
    str.reserve(N);
    for (int index = 0; index < N; index++)
    {
        str += alphabet[rand() % (alphabet.length())];
    }

答案 1 :(得分:0)

您需要一个TemplateModel变量,但您可以在全局中添加它(也就是说,在应用程序初始化期间只需一次),您可以在其中配置FreeMarker:

// Do these AFTER the cfg is ready otherwise: 

ObjectWrapper ow = cfg.getObjectWrapper();
// ow will be usually a DefaultObjectWrapper, which is a subclass of BeansWrapper
if (!(ow instanceof BeansWrapper)) {
    throw new IllegalStateException("The objet wrapper must implement " + BeansWrapper.class.getName() + " in this application.");
}
cfg.setSharedVariable("mu", ((BeansWrapper) ow).getStaticModels().get(MyUtils.class.getName()));

其中MyUtils可能类似于

public class MyUtils {

    public static String foo(String s) {
        return "foo " + s;
    }

    // ... further methods here

}

然后在所有模板中都可以执行此操作:

${mu.foo('bar')};

您还可以将getStaticModels()本身的结果添加为共享变量,例如,使用名称classes,然后在模板中添加${classes['com.example.MyUtils'].foo('bar')},但它的IMO太技术性了模板。

相关问题