【问题标题】:Get thymeleaf html file with all includes获取包含所有内容的 thymeleaf html 文件
【发布时间】: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


【解决方案1】:

如果您使用 Thymeleaf 项目创建了“标准”Spring Boot(例如,通过 https://start.spring.io),那么如果您将模板放入 src/main/resources/templates,则会自动解析模板

因此,如果您创建了 src/main/resources/templates/templates.html,那么您可以创建一个将使用该模板的控制器,如下所示:

@Controller
@RequestMapping("/")
public class MyController {

  @GetMapping("/get-template-html")
  public String getTemplateHtml() {
    return "templates"; // name of your template file without the .html extension
  }
}

如果您启动应用程序并访问 http://localhost:8080/get-template-html,您应该会看到模板的 HTML。

【讨论】:

  • 是的,我知道,但那不是我想要的。我需要一个端点来检索它,因为不同的项目使用该文件
  • 您想获得没有 Thymeleaf 处理的 raw 模板,以便您可以从一个项目到另一个项目进行 REST 调用并重新使用它?如果是这样,您不能创建一个共享的 Java 库吗?
  • 不知道,好像很好的解决办法,我只是按照老板说的去做,我只是实习生。
猜你喜欢
  • 1970-01-01
  • 2013-04-10
  • 1970-01-01
  • 2016-03-27
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多