开发者

freemarker: template Loader : load templates from zip file

开发者 https://www.devze.com 2023-01-25 11:29 出处:网络
is it possible to load freemarker templates from zip file? i want to zip all templates in a开发者_开发百科 single file and put it in my application.

is it possible to load freemarker templates from zip file?

i want to zip all templates in a开发者_开发百科 single file and put it in my application.

is it possible?


It might not be ideal, but if you would just load the text of the zipped template files you can instantiate a FreeMarkerTemplate from the String. I gave you an example of how it might be done below, but I suggest reading the freemarker documentation as well. (check the Getting Started tab)

i.e.

Configuration cfg = new Configuration();
//configuring default free marker configuration
cfg.setObjectWrapper(new DefaultObjectWrapper());

//construct template from string
String templateText = "";//load template text from zip file

Template template= new Template("sometemplate", new StringReader(templateText), cfg);

//your data model 
Object root = new Object(); 

//process template 
StringWriter out = new StringWriter(); 
template.process(new Object(), out); 

String renderedText= out.toString(); 


I don't know about a zip file, but you can load them up from a jar file using the 'classForTemplateLoading' feature:

public class MyLoader 
{
    private static Configuration cfg = new Configuration();

    static 
    {
         cfg.setClassForTemplateLoading( MyLoader.class, "/" );
    }

    public Template getTemplate( String path ) throws Throwable
    {
         return cfg.getTemplate(path);
    }
}

For example, if your template "MyTemplate.ftl" is in the 'com.mycode.templates' package, the path would be "/com/mycode/templates/MyTemplate.ftl".

So then you would jar up your 'source' tree as if it were classes, add the jar to your classpath and it should all just work.

0

精彩评论

暂无评论...
验证码 换一张
取 消