在处理之前将宏添加到现有模板

时间:2015-01-07 17:50:39

标签: java freemarker

  • 我有一个TemplateLoader getReader将返回一个有效的FTL,除了FTL中使用的宏的定义缺失。
  • 所有需要的宏定义将由外部源作为String传递。
  • 由于某些复杂的原因,我不允许更改TemplateLoader实现或更改配置对象(这意味着我必须以某种方式将String合并到Configuration#getTemplate本身的结果中

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

在致电String之前,我如何预先设定宏定义(或任何有效的FTL作为Template#process收到)?

1 个答案:

答案 0 :(得分:0)

事实证明,您可以将宏包装在虚构模板中,创建处理环境(而不是直接处理主模板),在处理环境中包含或导入虚构模板,然后处理:

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