如何获取包含全部引用片段的Thymeleaf HTML文件完整内容
Thymeleaf模板引入片段的正确实现方案
问题根源
你遇到的报错根本原因是两个:
- 直接通过
Files.readString读取主模板文件只能拿到文件原始文本,模板中引用的fragment(比如footer::footer)还是未解析的Thymeleaf标记,不会自动引入对应片段内容 - 后续使用StringTemplateResolver处理模板字符串时,该解析器仅能处理输入的字符串本身,没有配置片段文件的查找路径,无法定位到你存放在
templates目录下的其他片段文件,因此会抛出片段找不到的异常
方案1:直接使用默认TemplateEngine完成片段解析+变量渲染(最推荐)
SpringBoot自动配置的Thymeleaf默认已经内置了ClassLoaderTemplateResolver,默认会从classpath:/templates/目录下加载模板和对应的片段文件,不需要自己读取文件、也不需要手动创建TemplateEngine实例,直接注入使用即可:
// 直接注入Spring自动配置好的TemplateEngine @Autowired private TemplateEngine templateEngine; public String getRenderedHtml() { Context context = new Context(); // 填入所有你需要的变量 context.setVariable("expenseReportPdf", expenseReportPdf); context.setVariable("expensePdf", expensePdfList); context.setVariable("expenseImg", jpgFile); context.setVariable("amountCompanyCurrency", amountCompanyCurrency); context.setVariable("expenseIncurredList", expenseIncurredList); context.setVariable("expenseRiepiloghiList",expenseRiepiloghiList); context.setVariable("advancePayBigDecimal", advancePayBigDecimal); context.setVariable("dailyAllowanceList", dailyAllowanceList); context.setVariable("dailyAllowanceFlag", dailyAllowanceFlag); context.setVariable("logo",logo); context.setVariable("logoSmartex",logoSmartex); // 直接传入模板名称(不需要后缀,默认自动补.html),会自动解析所有引用的片段+渲染变量 return templateEngine.process("template", context); }
如果需要对外提供返回完整模板的接口,直接调用这个方法返回即可,不需要自己做文件读取操作。
方案2:单独获取合并了所有片段、无变量渲染的模板字符串
如果你确实需要先拿到没有渲染变量、仅合并了所有引用片段的完整模板文本,可以传入空的Context执行一次模板解析:
@Autowired private TemplateEngine templateEngine; @GetMapping(path = "/get-template-html") public String getTemplateHTMLEndpoint() { // 空上下文不会触发变量替换,只会解析引入的片段 return templateEngine.process("template", new Context()); }
后续你拿到这个完整模板字符串之后,再用StringTemplateResolver做变量渲染时,就不会再出现片段找不到的报错了,因为此时模板里已经没有fragment引用标记,所有片段内容已经被嵌入到主模板中。
内容的提问来源于stack exchange,提问作者Daniele Scalco
相关产品推荐
相关产品推荐

