【发布时间】:2021-11-14 00:22:28
【问题描述】:
大家好,我是 Thymeleaf 的新手,我的目标是有一个端点,它返回一个带有 html 文件内容的字符串。应该很容易,但是该文件 html 包含百里香代码并使用其他文件的片段,因此使用 Files.readString(path) 无法达到目标。
我怎样才能包含它们(我只想包含片段,我不必处理文件)?
这就是我到目前为止所做的:
@GetMapping(path = "/get-template-html")
public String getTemplateHTMLEndpoint() {
String templateHtml = "Problems reading template.html";
try {
String stringPath = new ClassPathResource("templates/template.html").getFile().getPath();
Path path = Path.of(stringPath);
templateHtml = Files.readString(path);
} catch (IOException e) {
e.printStackTrace();
}
return templateHtml;
}
但在我处理传递上下文的文件的另一种方法中,我收到关于片段“footer::footer”的错误
String templateHtml = callGetTemplateHTMLEndPoint();
StringTemplateResolver stringTemplateResolver = new StringTemplateResolver();
stringTemplateResolver.setTemplateMode(TemplateMode.HTML);
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(stringTemplateResolver);
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);
String renderedHtmlContent = templateEngine.process(templateHtml, context);
【问题讨论】:
-
您到底尝试了什么?如果您只想在 Spring Boot 中使用 Thymeleaf 片段,您可以查看我的一篇博客文章(例如 wimdeblauwe.com/blog/2021/09/14/…)以获取使用片段的示例。
标签: html spring spring-boot thymeleaf