繁体   English   中英

Spring Boot FreeMarker:如何即时使用自定义模板?

[英]Spring Boot FreeMarker: How to use custom template on the fly?

我想在我的 spring 启动应用程序中使用 freemarker。 模板将从数据库或文件中加载,但我如何将其与 SpringTemplateLoader 一起使用? 据我所知,总是期望文件在磁盘上的某个地方,但在我的例子中,它可以从不同的来源加载。

这是我的测试用例

    File testPdf = getResourceFile("template/test.ftl");
    assertThat(testPdf.exists()).isTrue();
    Map<String, String> model = new HashMap<>();
    model.put("firstName", "Dave");
    model.put("lastName", "Grohl");

    String replacedString = FreeMarkerUtil.getContentFromTemplate(Files.readAllBytes(testPdf.toPath()) , model);
    assertThat(replacedString).isEqualTo(expectedReplacedString);

我正在尝试使用需要 Resourceloader 和 templateLoaderPath 的 SpringTemplateLoader,但我没有路径,我希望从 byte[] 加载模板

public static String getContentFromTemplate(byte[] template, Map<String, String> model){
    ByteArrayResource templateResource = new ByteArrayResource(template);
    SpringTemplateLoader loader = new SpringTemplateLoader(templateResource, )
    
    
}

或者我是否需要将 ftl 存储在磁盘上并在 FreeMarker 的 Configuration 中配置此路径?

FreeMarker 不假定文件来自文件。 从哪里加载模板取决于TemplateLoader实现。 因此,您可能希望配置 FreeMarker 以使用您自己的实现。

请注意,也可以使用Template构造函数直接从String创建模板。 在某些应用程序中,这是最简单的解决方案。 这样做的缺点是不能通过名称从其他模板引用此类模板(例如通过#import#include )。 显然,对于此类Template对象,FreeMarker 不会为您进行缓存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM