Spring Boot 使用thymeleaf

ctrl + n class查询
ctrl + g 快速定位到行

1. 引入thymeleaf
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2. thymeleaf使用

org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration

@Configuration
@EnableConfigurationProperties({ThymeleafProperties.class})
@ConditionalOnClass({TemplateMode.class})
@AutoConfigureAfter({WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class})
public class ThymeleafAutoConfiguration {
	...
}

org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
    private Charset encoding;
    private boolean cache;
    ...
}

只需要把html文件放在classpath:/templates/文件夹下就可以使用了

3. thymeleaf语法

http://www.thymeleaf.org

先要导入thymeleaf名称空间

<html xmlns="http://www.thymeleaf.org">
...

th:text 改变当前元素内容

<!--<p>Hello, <span th:text="${session.user.name}">Sebastian</span>!</p>-->
<p>Hello, [[${session.user.name}]]!</p>

[[…]] 相当于 th:text=
[(…)] 相当于 th:utext=

th: 任意html属性:替换原生属性的值
在这里插入图片描述
${}
*{}

<div th:object="${session.user}">
	<!--${session.user.firstName}-->
  <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
	<!--${session.user.firstName},#object作为th:object选择的对象-->
  <p>Name: <span th:text="${#object.firstName}">Sebastian</span>.</p>
	<!--${session.user.lastName}-->
  <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
	<!--${session.user.nationality}-->
  <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>

	<!--${session.user.name}如果没有执行对象选择,${}=*{}-->
	<p>Name: <span th:text="*{session.user.name}">Sebastian</span>.</p>
</div>

#{} 获取国际化内容
@{} 定义url

三元运算符:
(if) ? (then)
(if) ? (then) : (else)
(value) ? : (defaultvalue)

<tr th:each="prod : ${prods}">
  <td th:text="${prod.name}">Onions</td>
  <td th:text="${prod.price}">2.41</td>
  <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html 官方手册

要修改模板实时生效:禁用thymeleaf的缓存spring.thymeleaf.cache=falsectrl+f9重新编译

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值