thymeleaf 使用

本文介绍了如何在Spring Boot项目中集成Thymeleaf模板引擎,通过引入NekoHTML和OGNL等依赖,配置文件设置模板路径和模式,然后在代码中创建TemplateEngine实例,动态填充数据并生成HTML内容。示例展示了如何处理模板变量并与HTTP响应结合使用。
摘要由CSDN通过智能技术生成

1、引入依赖

<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.22</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>ognl</groupId>
    <artifactId>ognl</artifactId>
    <version>3.2.1</version>
</dependency>

2、配置文件 .yml

spring:
  thymeleaf:
    encoding: UTF-8
    cache: false
    # 检查模板是否存在,然后再呈现
    check-template-location: true
    prefix: classpath:/word/
    suffix: .html
    mode: LEGACYHTML5
    servlet:
      content-type: text/html

3代码

private final static TemplateEngine engine = new TemplateEngine();
 @Override
    public void AISave(String materialCarBatchId, String compilationTemplateId, HttpServletResponse response) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("title", "测试");
            Context context = new Context();
            context.setVariables(dataMap);
            String html = engine.process("<p th:text='${title}'></p>", context);

       }

注意

如果引入下面的则只能根据2配置文件查找到项目内的模板

@Autowired
private SpringTemplateEngine templateEngine;
Context context = new Context(Locale.getDefault(), dataMap);

String html = templateEngine.process("test.html", context);

附上  test.html 代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
<p th:text="${title}">${title}</p>
<table border="1">
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Age</th>
    </tr>
<!-- 遍历list    <tr th:each="u : ${archiveCarDetailList}">
        <td th:text="${u.title}"></td>
        <td th:text="${u.title}"></td>
        <td th:text="${u.title}"></td>
    </tr>-->
</table>
</body>
</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

【这个世界会好的】

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值