【问题标题】:Prepend Macros to existing Template before processing在处理之前将宏添加到现有模板
【发布时间】:2015-01-07 17:50:39
【问题描述】:
  • 我有一个TemplateLoader,他的getReader 将返回一个有效的 FTL,除了 FTL 中使用的宏定义丢失。
  • 所有需要的宏定义都将由外部源作为String 传递。
  • 由于一些复杂的原因,我不允许更改 TemplateLoader 实现或更改配置对象(这意味着我必须以某种方式将 String 合并到 Configuration#getTemplate 本身的结果中)。

我看到有一个 Template#addMacro 方法,但是它说它在内部使用并期望一个 Macro (我有一个 String 定义了多个宏,自己解析它似乎不是合理的方法)。

我如何在调用Template#process 之前添加宏定义(或作为String 接收的任何有效FTL)?

【问题讨论】:

    标签: java freemarker


    【解决方案1】:

    原来你可以将宏包装在虚构的模板中,创建处理环境(而不是直接处理主模板),在处理环境中包含或导入虚构的模板,然后处理:

    String macrosSource = getMacros();
    // Needed to create the fictional template, has no real purpose
    Configuration wrapper = new Configuration(Configuration.VERSION_2_3_21);
    wrapper.setObjectWrapper(new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_21).build());
    
    // Fictional template which has the only purpose to hold your macroSource
    Template macrosFictionalTemplate = new Template(null, macroSource, wrapper);
    
    // Get template as you normally would
    Template mainTemplate = configuration.getTemplate("main_template");
    
    // Create a processing environment. This is an object on which you can call
    // .process just as you can on a template. The model and out are the same as
    // Template#process(model, out)
    Environment mainTemplateEnvironment = mainTemplate.createProcessingEnvironment(model, out);
    
    // Either include -> macros will be accessible as top-level
    mainTemplateEnvironment.include(macrosFictionalTemplate);
    // Or import -> macros will be accessible using macros.macroName
    mainTemplateEnvironment.importLib(macrosFictionalTemplate, "macros");
    
    // Process everything
    mainTemplateEnvironment.process();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 2020-06-01
      • 2016-03-15
      相关资源
      最近更新 更多