Freemarker URL模板加载器 [英] Freemarker URL Template Loader

查看:275
本文介绍了Freemarker URL模板加载器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个或多个URL加载Freemarker模板,因此我将URLTemplate加载器类子类化,并覆盖getURL(..)方法以返回目标URL(请参见下文).然后,我将该类的几个实例添加到多模板加载器中,并将其添加到Freemarker配置中.当第一个URL返回模板但没有调用其他模板加载器时,此方法很好用.我做错了什么?我正在通过Restlet框架使用Freemarker v2.3.

I would like to load Freemarker templates from one or more URLs so I subclassed the URLTemplate loader class and overrode the getURL(..) method to return the target URL (see below). I then added a couple of instances of this class to a multi template loader and added that to the Freemarker config. This works fine when the first URL returns a template but when it doesn't none of the other template loaders are called. What have I done wrong? I'm using v2.3 of Freemarker via the Restlet framework.

:    :     :    :     :    :     :    :     :    :     
TemplateLoader[] loaders = new TemplateLoader[] {
    new MyTemplateLoader(new URL(request.getRootRef() + app.getRoot())),
    new MyTemplateLoader(new URL(request.getRootRef() + "/"))
};

freemarkerConfig.setTemplateLoader(new MultiTemplateLoader(loaders));  

:    :     :    :     :    :     :    :     :    :     

public class MyTemplateLoader extends URLTemplateLoader {
    private URL root;

    public MyTemplateLoader(URL root) {
        super();
        this.root = root;
    }

    @Override
    protected URL getURL(String template) {
        try {
            URL tu = new URL(root,  "./" + template);
            return tu;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }
}

推荐答案

如果TemplateLoader.findTemplateSource返回null,则认为该模板丢失.如果返回非null对象,则MultiTemplateLoader假定已找到模板.对于URLTemplateLoaderfindTemplateSource仅返回getURL的作用.因此,您必须检查目标是否存在,如果不存在,请返回null作为URL.这对于ClassTemplateLoader效果很好,因为getResource返回缺少资源的null URL.但是通常(如果您不知道使用哪种URL),必须打开URLConnection,然后打开connect(),以查看目标是否存在.或者至少我猜想大多数URLSrteamHandler -s都会检查目标点是否存在.

A template is considered to be missing if TemplateLoader.findTemplateSource returns null for it. If it returns a non-null object, then MultiTemplateLoader assumes that it has found the template. In the case of URLTemplateLoader, findTemplateSource just returns what getURL does. So you have to check if the target exists, and then return null as URL if it doesn't. This works well for ClassTemplateLoader because getResource returns null URL for missing resources. But in general (if you don't know what kind of URL do you have) you will have to open an URLConnection and then connect() to see if the target exists. Or at least I guess that most URLSrteamHandler-s will check if the target exists at that point.

这篇关于Freemarker URL模板加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆