html中如何引入css或者js
比如我们需要引入jquey和bootstrap,资源文件结构
image.png
页面中使用@默认从static下面寻找资源文件.
html,其中src路径在我们不启动服务的时候,直接通过src可以访问到资源文件,当启动服务的时候模板引擎将th:ref的属性替换掉默认的ref属性
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>
<link rel="stylesheet" type="text/css" media="all"
href="../../static/plugins/bootstrap/css/bootstrap.css" th:href="@{/plugins/bootstrap/css/bootstrap.css}" />
</head>
<body>
<table class="table">
<tr>
<td class="active">测试1</td>
<td class="success">测试2</td>
<td class="warning">测试3</td>
<td class="danger">测试4</td>
<td class="info">测试5</td>
</tr>
</table>
</body>
<script type="application/javascript" th:src="@{/plugins/jquery/jquery-3.3.1.min.js}" src="../../static/plugins/jquery/jquery-3.3.1.min.js" ></script>
<script type="application/javascript" th:src="@{/plugins/bootstrap/js/bootstrap.js}" src="../../static/plugins/bootstrap/js/bootstrap.js"></script>
<script type="application/javascript">
$(function(){
console.log($);
})
</script>
</html>
获取contentpath
如果有contentpath,需要加上项目名字的时候,应该怎么获取
<span th:text="${#httpServletRequest.getScheme() + '://' + #httpServletRequest.getServerName() + ':' + #request.getServerPort() + #request.getContextPath() + '/'} "
id="contextPath"></span>
thymeleaf中支持多种内置对象,比如
- ctx:上下⽂对象。
- vars:上下⽂变量。
- locale:上下⽂区域设置。
- request :(仅在Web Contexts中)HttpServletRequest对象
- response:(仅在Web上下⽂中)HttpServletResponse对象。
- session :(仅在Web上下⽂中)HttpSession对象。
-
servletContexte :(仅在Web上下⽂中)ServletContext对象
...
我们可以从这些内置对象中获取到比如session中的当前用户对象;
image.png
欢迎您<span th:text="${#session.getAttribute('loginUser')}"></span>
页面跳转路径需要这样写
<a href="" th:href="${#httpServletRequest.getContextPath()+'/test'}">跳转</a>
引入公共代码片段
比如我们希望引入一个页面的头部或者尾部的公共部分
首先在需要引入的html片段定义一个名称
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>common</title>
</head>
<body>
<div th:fragment="nav" class="navbar navbar-default navbar-static-top">
公共部分的html片段,名称为nav
</div>
页面中去引入此片段,使用th:insert 或者th:replace均可,insert唯一的区别是插入宿主片段中,而replace是替换掉宿主的片段.
欢迎您<span th:text="${#session.getAttribute('loginUser')}"></span>
<br/>
<div th:insert="~{common/common :: nav}"></div>
<table class="table">
<tr>
<td class="active">测试1</td>
<td class="success">测试2</td>
<td class="warning">测试3</td>
<td class="danger">测试4</td>
<td class="info">测试5</td>
</tr>
</table>
image.png
用法
- ~{templatename :: selector} 前面是模板名称,后面是选择器
- ~{:: selector} 不指定模板从当前页面查找
片段引入还有其他的写法,可以不定义片段直接使用选择器的方式
比如在common中同样有这样的一个代码片段,但是没有定义却有id
<div id="footer" >
© 2018 今天天气还不错
</div>
那么可以这样引用
//代表从common/common 的页面中,寻找Id 为footer的字段
<div th:replace="~{common/common :: #footer}"></div>