Thymeleaf模板引擎text语法全梳理
官方文档
开源项目
thymeleaf 开发多数据源模板:https://github.com/boommanpro/thymeleaf-template
Spring Boot Linux 部署脚本:https://github.com/boommanpro/linux-spring-boot-startup-generator
核心代码拆解
pom引入
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
</dependency>
for.txt
[#th:block th:each="item : ${users}"]
- [#th:block th:utext="${item}" /]
[/th:block]
junit test
@Test
public void originalTemplate() throws IOException {
String content = IOUtils.toString(new ClassPathResource("thymeleaf/for.txt").getStream());
StringTemplateResolver templateResolver = new StringTemplateResolver();
templateResolver.setTemplateMode("TEXT");
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
Dict set = Dict.create().set("users", Arrays.asList("Alice", "Bob", "Charlie"));
String process = templateEngine.process(content, new Context(Locale.CHINA, set));
System.out.println(process);
}
语法讲解
1. 变量引用
Dear [(${name})],
Please find attached the results of the report you requested
with name "[(${report.name})]".
Sincerely,
The Reporter.
2. if语法
这里可以转义,也可以不转义
[# th:if="${120>user.age}"]
Congratulations!
[/]
[# th:if="${120<user.age}"]
Congratulations!
[/]
3. 循环语法
压缩版本
[# th:each="item : ${items}"]
- [(${item})]
[/]
完全版本
[#th:block th:each="item : ${items}"]
- [#th:block th:utext="${item}" /]
[/th:block]
4. 注释语法
/*[- */
var msg = "This is shown only when executed statically!";
/* -]*/
/*[- Note the user is obtained from the session, which must exist -]*/