Thymeleaf使用&语法
只要把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;
使用:
- 导入thymeleaf的命名空间:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
- 使用thymeleaf语法:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>success</title>
</head>
<body>
<h1>你好,执行成功!</h1>
<div th:text="${hello}">这是显示欢迎信息</div>
<!--/*@thymesVar id="hello" type=""*/-->
<div th:text="${hello}">我跟好</div>
</body>
</html>
- 语法规则
- th:text : 改变当前元素里面的文本内容;
- th: 任意html属性;来替换原生属性的值;
- 扩展SpringMVC
<mvc:view-controller path="/hello" view-name="success"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
在springboot上面的就可以通过编写配置类来实现
- 配置类(@Configuration)是webMvcConfigurerAdapter类型;不能标注@EnableWebMvc
- 既保留了所有的自动配置,也能用我们扩展的配置;
- 容器中所有的webMvcConfigurer都会一起起作用
- 我们的配置类也会被调用;
效果:SpringMVC的自动配置和我们扩展配置都会起作用。
- 如何修改springboot的默认配置
模式:
- springboot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@bean、@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;
- 在springboot中会有非常多的xxxconfiguration帮助我们扩展配置。
thymeleaf抽取公共页面元素:
1.抽取公共片段
<div th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</div>
2. 引入公共片段
<div th:insert="~{footer :: copy}"></div>
~{templatename::selector}:模板名::选择器
~{templatename::fragmentname}:模板名::抽取片段名
3.默认效果
insert的功能片段在div标签中
如果使用th:insert等属性进行引入,可以不用写~{};
行内写法可以加上:[[~{}]];[(~{})]
三种引入功能片段的th属性:
- th:insert:将公共片段整个插入到声明引入的元素中。
- th:replace:将声明引入的元素替换为公共片段。
- th:include:将被引入的片段的内容包含到找个标签中。
<div th:insert="footer :: copy">
©2010 The Good thymes Virtural Grocery
</div>
引入方式
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>
三种引入方式的效果
<body> ...
<div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
</div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
<div>
© 2011 The Good Thymes Virtual Grocery
</div>
</body>
thymeleaf中侧边导航的高亮显示
通过在a标签中添加三元逻辑判断运算符,给添加抽取的公共片段中添加参数进行识别。
<a class="nav-link active"
th:href="@{/mainpage.html}"
<!--这块通过三元逻辑运算符判断是否选中该页面。-->
th:class="${activeuri=='mainpage.html'?'nav-link active':'nav-link'}">
<span class="sr-only">(current)</span>
</a>
当别的页面引用该公共片段时,传入响应的参数
<!--引入侧边导航sidebar-->
<div th:replace="commons/bar::#sidebar(activeuri='mainpage.html')"></div>