(项目实战干货)Spring boot 中Thymeleaf 模板 html 标签使用

Spring boot 中Thymeleaf 模板 html 标签使用

​ 在Spring boot 项目开发中,会常常使用到Thymeleaf模板。在对Thymeleaf模板标签的使用技巧,有的人不是很熟悉。这篇文章专门介绍一下模板标签的使用技巧。静态原型中(html页面)Thymeleaf元素与html元素相结合使用的说明与代码例子。文中会提高大量Thymeleaf标签的属性介绍和使用的逻辑示例代码。
pom.xml 项目中使用的Thymeleaf版本

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.11.RELEASE</version>
        </dependency>

1 文字内联标签引入

​ Thymeleaf模板中的使用文字内联标签,需要在使用的html元素上加上文字内联标签标记。

<body th:inline="text">            
  ...
</body>

<script th:inline="javascript">
  ... 
</script>

2 逻辑类标签使用

2.1 th:block与th:each [# th:each=""]循环

th:block仅是一个属性容器,允许模板开发人员指定他们想要的任何属性。Thymeleaf执行完成后,th:block标签不会在html页面中保存下来,它只是逻辑标签。

th:each是循环逻辑标签,负责迭代集合中数据到显示到html页中来。

th:each=“迭代器名称: 集 合 元 素 的 名 称 " 。 例 如 : t h : e a c h = " u s e r : {集合元素的名称}"。 例如: th:each="user: "th:each="user:{users}”

<body th:inline="text">
<table>
   <tr> 
        <td>名称</td>
        <td>地址</td>
    </tr>    
  <th:block th:each="user:${users}">
    <tr>
        <td th:text="${user.name}">...</td>
        <td th:text="${user.address}">...</td>
    </tr>
  </th:block>
</table>
</body>

javascript[# th:each=""]循环遍历也可以使用文字关联标签。

例如:[# th:each=“item: l i s t " ] [ ( {list}"] [( list"][({item.name})]” [/]

<script  th:inline="javascript">  
  [# th:each="item:${users}"] 
    [(${item.name})]  
    [(${item.address})]  
   [/]
</script>

引用名称+Stat 例子:itemStat 遍历循环的公共属性引用名字

  • 当前的迭代索引,从0开始。这是index属性。
  • 从1开始的当前迭代索引。这是count属性。
  • 迭代变量中元素的总数。这是size属性。
  • 每次迭代的iter变量。这是current属性。
  • 当前迭代是偶数还是奇数。这些是even/odd布尔属性。
  • 当前迭代是否是第一个。这是first布尔属性。
  • 当前迭代是否为最后一次。这是last布尔属性。
<table>
   <tr> 
        <td>名称</td>
        <td>地址</td>
    </tr>    
  <th:block th:each="user:${users}">
    <tr th:class="${userStat.odd}?'odd'"><--判断是否是偶数列-->
        <td th:text="${user.name}">...</td>
        <td th:text="${user.address}">...</td>
    </tr>
  </th:block>
</table>

2.2 th:text 与 [(${name})] 功能

th:text显示文本内容标签,可以将循环中遍历的内容通过标签的形式显示在html页面中。

[(${name})]也可以使用文本标签的形式将内容显示在html页面中,这个方法更加灵活,但是前提必须要在body元素中加入th:inline="text"标记参考 1文字内联标签引入。

<table>
   <tr> 
        <td>名称</td>
        <td>地址</td>
    </tr>    
  <th:block th:each="user : ${users}">
    <tr>
        <td th:text="${user.name}">...</td>    //th:text 标签使用方法
        <td>[(${user.address})]</td>           //[(${引用})]文字内联使用方法
    </tr>
  </th:block>
</table>

2.3 @{}字符串拼接语法

@{'字符串'+引用内容}将固定的字符串与引用变量组合成新的字符串内容。

​ 例如@{’…/WbsItemManageContorller/finduser?id=’+${item.id}}

​ html 显示的字符串’…/WbsItemManageContorller/finduser?id=1’

<table>
   <tr> 
        <td>名称</td>
        <td>地址</td>
        <td>编辑</td>
    </tr>    
  <th:block th:each="user : ${users}">
    <tr>
        <td th:text="${user.name}">...</td>    //th:text 标签使用方法
        <td>[(${user.address})]</td>           //[(${引用})]文字内联使用方法
        <td>
            <a th:href="@{'../WbsItemManageContorller/finduser?id='+${user.id}}">
                修改
            </a>
        </td>         
    </tr>
  </th:block>
</table>

例子 th:onClick:

<table>
   <tr> 
        <td>名称</td>
        <td>地址</td>
        <td>编辑</td>
    </tr>    
  <th:block th:each="user:${users}">
    <tr>
        <td th:text="${user.name}">...</td>    //th:text 标签使用方法
        <td>[(${user.address})]</td>           //[(${引用})]文字内联使用方法
        <td>
            <a th:href="@{'../WbsItemManageContorller/finduser?id='+${user.id}}">
                修改
            </a>
            <div th:onClick="@{'ondel('+${item.id}+')'}">删除</div>
            //@{}字符串拼接语法
        </td>         
    </tr>
  </th:block>
</table>

2.4 th:if判断标签 [# th:if=]

​ th:if通过条件判断,来决定符合条件的元素是否存在于html页面中来。或者通过 [# th:if=] 文字标签来判断范围内的内容是否显示在html页面中。可以在block容器中写 th:if判断语法,也可以在html 元素中写th:if 判断语法。

gt:great than(大于)>

ge:great equal(大于等于)>=

eq:equal(等于)==

lt:less than(小于)<

le:less equal(小于等于)<=

ne:not equal(不等于)!=

​ 例如: <th:block th:if="${user.id}>10">

<table>
   <tr> 
        <td>名称</td>
        <td>地址</td>
        <td>编辑</td>
    </tr>    
  <th:block th:each="user:${users}">
     //判断用户id大于是否大于10
    <th:block th:if="${user.id}>10">   元素判断标签使用
    <tr>
        <td th:text="${user.name}">...</td>    //th:text 标签使用方法
        <td>[(${user.address})]</td>           //[(${引用})]文字内联使用方法
        <td>
            <a th:href="@{'../WbsItemManageContorller/finduser?id='+${user.id}}">
                修改
            </a>
            <div th:onClick="@{'ondel('+${item.id}+')'}">删除</div>
            //@{}字符串拼接语法
        </td>         
    </tr>
    </th:block>  判断结束标签元素
  </th:block>
</table>

key javascript[# th:if=]文字逻辑

<script th:inline="javascript">  
  [# th:each="item:${users}"] 
  `[# th:if="${item.id}>10"] ` 
        [(${item.name})]  
        [(${item.address})]  
    [/]
   [/]
</script>

2.5 标签追加和前置设置

有些业务逻辑中需要在html属性中进行动态的追加属性内容,我们可以使用到th:attrappendth:attrprepend来进行这样的逻辑操作

<input type="button" value="提交"
 class="btn" 
 th:attrappend="class=${' ' + cssStyle}" />
 <input type="button" value="提交"
  class="btn warning" />

3 普通标签使用

3.1 input 常用标签

标签说明备注
th:valuevalue 属性th:value="${item.itemid}"
th:id替换id<input th:id="'xxx' + ${collect.id}"/>
th:text文本替换<p th:text="${collect.description}">description</p>
th:selectedselect选择框选中th:selected="(${xxx.id} == ${configObj.dd})"
th:action表单提交的地址<form action="subscribe.html" th:action="@{/subscribe}">
th:checked复选框选中th:checked="${user.active}"
<form action="subscribe.html">
   <input type="text" name="name" th:value="${user.name}"/>
   <select name="deptid">
       <option value="1" th:selected="(${user.deptid}==1)">部门a</option>
       <option value="2">部门b</option>
       <option value="3">部门c</option>
   </select>   
    
   <input type="checkbox" name="z1" value=""/> 
   <input type="hidden" name="z2" value=""/> 
   <input type="radio" name="z3" value=""/> 
   <input type="button"  value="提交" th:onclick="@{'ondel('+${item.id}+')'}"/> 
</form>
   
<input type="checkbox" name="option2" checked />
<input type="checkbox" name="active"
 th:checked="${user.active}" />  

<option value="1" selected >部门a</option>  
<option value="1" th:selected="(${user.deptid}==1)">部门a</option> //select 判断返显示

在html属性标签中有判断是否为false和true的情况。以下标签都可以使用 if 的方式判断true与false的情况。

th:asyncth:autofocusth:autoplay
th:checkedth:controlsth:declare
th:defaultth:deferth:disabled
th:formnovalidateth:hiddenth:ismap
th:loopth:multipleth:novalidate
th:nowrapth:openth:pubdate
th:readonlyth:requiredth:reversed
th:scopedth:seamlessth:selected

3.2 常用标签

Thymeleaf所有标签合集,这些为在Thymeleaf中可以使用和引用的标签。

th:abbrth:acceptth:accept-charset
th:accesskeyth:actionth:align
th:altth:archiveth:audio
th:autocompleteth:axisth:background
th:bgcolorth:borderth:cellpadding
th:cellspacingth:challengeth:charset
th:citeth:classth:classid
th:codebaseth:codetypeth:cols
th:colspanth:compactth:content
th:contenteditableth:contextmenuth:data
th:datetimeth:dirth:draggable
th:dropzoneth:enctypeth:for
th:formth:formactionth:formenctype
th:formmethodth:formtargetth:fragment
th:frameth:frameborderth:headers
th:heightth:highth:href
th:hreflangth:hspaceth:http-equiv
th:iconth:idth:inline
th:keytypeth:kindth:label
th:langth:listth:longdesc
th:lowth:manifestth:marginheight
th:marginwidthth:maxth:maxlength
th:mediath:methodth:min
th:nameth:onabortth:onafterprint
th:onbeforeprintth:onbeforeunloadth:onblur
th:oncanplayth:oncanplaythroughth:onchange
th:onclickth:oncontextmenuth:ondblclick
th:ondragth:ondragendth:ondragenter
th:ondragleaveth:ondragoverth:ondragstart
th:ondropth:ondurationchangeth:onemptied
th:onendedth:onerrorth:onfocus
th:onformchangeth:onforminputth:onhashchange
th:oninputth:oninvalidth:onkeydown
th:onkeypressth:onkeyupth:onload
th:onloadeddatath:onloadedmetadatath:onloadstart
th:onmessageth:onmousedownth:onmousemove
th:onmouseoutth:onmouseoverth:onmouseup
th:onmousewheelth:onofflineth:ononline
th:onpauseth:onplayth:onplaying
th:onpopstateth:onprogressth:onratechange
th:onreadystatechangeth:onredoth:onreset
th:onresizeth:onscrollth:onseeked
th:onseekingth:onselectth:onshow
th:onstalledth:onstorageth:onsubmit
th:onsuspendth:ontimeupdateth:onundo
th:onunloadth:onvolumechangeth:onwaiting
th:optimumth:patternth:placeholder
th:posterth:preloadth:radiogroup
th:relth:revth:rows
th:rowspanth:rulesth:sandbox
th:schemeth:scopeth:scrolling
th:sizeth:sizesth:span
th:spellcheckth:srcth:srclang
th:standbyth:startth:step
th:styleth:summaryth:tabindex
th:targetth:titleth:type
th:usemapth:valueth:valuetype
th:vspaceth:widthth:wrap
th:xmlbaseth:xmllangth:xmlspace

3.3 工具内部对象

在Thymeleaf中为我为提供了一组非常使用的工具对象。帮助我们进行编码

  • #execInfo:有关正在处理的模板的信息。
  • #messages:用于获取变量表达式内的外部化消息的方法,与使用#{…}语法获得消息的方法相同。
  • #uris:用于转义部分URL / URI的方法
  • #conversions:用于执行已配置的转换服务(如果有)的方法。
  • #datesjava.util.Date对象的方法:格式化,组件提取等。
  • #calendars:类似于#dates,但用于java.util.Calendar对象。
  • #numbers:格式化数字对象的方法。
  • #stringsString对象的方法:包含,startsWith,前置/附加等。
  • #objects:一般对象的方法。
  • #bools:布尔值评估的方法。
  • #arrays:数组方法。
  • #lists:列表方法。
  • #sets:套方法。
  • #maps:地图方法。
  • #aggregates:用于在数组或集合上创建聚合的方法。
  • #ids:用于处理可能重复的id属性的方法(例如,由于迭代的结果)。
  • 15
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 18
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zht_bs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值