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

Prepend Macros to existing Template before processing

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

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

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

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