thymeleaf自学笔记

1  如何引入css、js文件

URL

URL在Thymleaf中是第一类公民,有其专有的表达式语法@{...}

共存在2大类URL:

  • 绝对URL http://www.your.domain
  • 相对URL,分为四类 
    • 相对于页面 user/login.html
    • 相对于上下文 /itemdetails?id=3 (服务的上下文名会被自动添加)
    • 相对于服务器 ~/billing/processInvoice (可以调用在另一个context(application)中的URL)
    • 相对于协议 //code.jquery.com/jquery-2.0.3.min.js
    • 服务器相关的URL与上下文相关的URL非常相似,只是它们不假定URL要链接到应用程序上下文中的资源,因此允许链接到同一服务器中的不同上下文:

      <a th:href="@{~/billing-app/showDetails.html}">
      

      当前应用程序的上下文将被忽略,因此尽管应用程序部署在http:// localhost:8080 / myapp,但该URL将输出:

      <a href="/billing-app/showDetails.html">
      
      

默认内置对象

<div class="showing">
<h2>格式化日期</h2>
直接输出日期 ${now}:
<p th:text="${now}"></p>
默认格式化 ${#dates.format(now)}:
<p th:text="${#dates.format(now)}"></p>
自定义格式化 ${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}:
<p th:text="${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}"></p>
</div>

4  th:fragment与 th:include配合使用引入页头、页眉
注意:第一个pagination为上述公共部分的文件名,第二个pagination为th:fragment的值。这样便可以解决公共部分代码的抽取。

fragment加载语法如下:

  • templatename::selector:”::”前面是模板文件名,后面是选择器
  • ::selector:只写选择器,这里指fragment名称,则加载本页面对应的fragment
  • templatename:只写模板文件名,则加载整个页面
  1. ================== fragment语法 =============================
    
    <!-- 语法说明 "::"前面是模板文件名,后面是选择器 -->
    
    <div th:include="template/footer::copy"></div>
    
    <!-- 只写选择器,这里指fragment名称,则加载本页面对应的fragment -->
    
    <div th:include="::#thispage"></div>
    
    <!-- 只写模板文件名,则加载整个页面 -->
    
    <div th:include="template/footer"></div>
    
    ================= 加载块 ============================
    
    
    <span id="thispage">
    
    div in this page.
    
    </span>

th:include 和 th:replace都是加载代码块内容,但是还是有所不同

  • th:include:加载模板的内容: 读取加载节点的内容(不含节点名称),替换div内容
  • th:replace:替换当前标签为模板中的标签,加载的节点会整个替换掉加载他的div 

公共部分如下:



<!-- th:fragment 定义用于加载的块 -->
<span th:fragment="pagination">
the public pagination
</span>

引用时如下:

================= th:include 和 th:replace============================
<!-- 加载模板的内容: 读取加载节点的内容(不含节点名称),替换<div>的内容 -->
<div th:include="pagination::pagination">1</div>
<!-- 替换当前标签为模板中的标签: 加载的节点会整个替换掉加载他的<div> -->
<div th:replace="pagination::pagination">2</div>

猜你喜欢

转载自blog.csdn.net/zhousenshan/article/details/82725376