TemplateLoader
getReader
将返回一个有效的FTL,除了FTL中使用的宏的定义缺失。String
传递。TemplateLoader
实现或更改配置对象(这意味着我必须以某种方式将String
合并到Configuration#getTemplate
本身的结果中我看到有一个Template#addMacro
方法,但它说它在内部使用并期望Macro
(我有一个String
定义了多个宏,我自己解析它看起来不是合理的方式)。
在致电String
之前,我如何预先设定宏定义(或任何有效的FTL作为Template#process
收到)?
答案 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();