【问题标题】:freemarker: template Loader : load templates from zip filefreemarker:模板加载器:从 zip 文件加载模板
【发布时间】:2011-05-11 20:40:29
【问题描述】:

是否可以从 zip 文件加载 freemarker 模板?

我想将所有模板压缩到一个文件中并将其放入我的应用程序中。

有可能吗?

【问题讨论】:

    标签: freemarker


    【解决方案1】:

    这可能并不理想,但如果您只需要 load the text of the zipped template 文件,您可以从字符串中实例化 FreeMarkerTemplate。我在下面给了你一个例子,但我建议你也阅读the freemarker documentation。 (检查“入门”选项卡)

    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(); 
    

    【讨论】:

      【解决方案2】:

      我不知道 zip 文件,但您可以使用“classForTemplateLoading”功能从 jar 文件中加载它们:

      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);
          }
      }
      

      例如,如果您的模板“MyTemplate.ftl”在“com.mycode.templates”包中,则路径将为“/com/mycode/templates/MyTemplate.ftl”。

      那么你可以把你的“源”树当成类,把它添加到你的类路径中,它应该就可以工作了。

      猜你喜欢
      • 2013-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      • 2010-09-26
      • 2013-01-23
      • 1970-01-01
      • 2017-04-20
      相关资源
      最近更新 更多