Thymeleaf

模板引擎,相当于jsp的视图解析器,工作原理如下:

thymeleaf使用:

1. 引入启动器依赖:spring-boot-starter-thymeleaf

2. ThymeleafProperties.java中规定了能够解析的文件的前缀和后缀:

也就是说只有在类路径templates文件夹下的html文件才能被thymeleaf引擎解析

3. 在html标签中加入thymeleaf的命名空间:xmlns:th="http://www.thymeleaf.org",加入后有语法提示(也可不加)

语法

th:html属性,html有的属性,thymeleaf基本都有。

表达式语法:

${ }:变量表达式

@{ }:链接表达式

*{ }:对象表达式

#{ }:消息表达式

~{ }:代码块表达式

开发期间为方便调试,修改引擎模板页面需要实时生效,做如下操作:

1. 禁用模板引擎缓存,在配置文件中:spring.thymeleaf.cache=false

2. 页面修改完成后,ctrl+F9重新编译

${ }:变量表达式

th:text = "${user.name}",行内写法:[[${user.name}]]

@{ }:链接表达式

@{/}:表示根路径

替换url路径变量:@{/mas/user/{group}/{id}(group=${group},id=${d})}

替换url参数:@{/mas/user?name={name}&age={age}(name=${name},age=${age})}

相当于:@{/mas/user(name=${name},age=${age})}

*{ }:对象表达式

用预先选择的对象代替上下文容器中的属性,类似${ },不同的是如果上层中有object,则查询使用object中的属性

<div th:object="${user}">
    <p th:text="*{name}"></p>
</div>
<!--  等价于  -->
<p th:text="${user.name}"></p>

#{ }:消息表达式

显示在classpath下的properties配置文件中的静态文本。默认显示的内容为配置文件在classpath下的messages.properties中。

也可在配置文件中指定配置文件在resoures下的路径和名称:spring.messages.basename=i18n.mainxxx

如:<p th:text="#{home.msg}" ></p>

~{ }:代码块表达式

1. 在template中common文件夹下common.html中定义代码块片段:

<div th:fragment="topbar">
    <div>xxx</div>
</div>

2.在其他html文件中引用:~{template下模板的完整路径名称 :: 代码块名称 / 代码块id名} 或 template下模板的完整路径名称 :: 代码块名称 / 代码块id名。

<div th:replace="~{common/common::topbar}"></div>
<div th:insert="common/common::topbar"></div>

th:insert 将代码块插入元素中

th:include 将代码块中的内容插入元素

th:replace 将元素替换成代码块

操作

文本:+  连接,th:text="${a} + ' xxx' + ${b}"

算术:+ - * / %

布尔:and  or  not  !

比较:>,<,>=,<=,==,!=(gt,lt,ge,le,eq,ne)

条件:(if) ? (then)   ||   (if) ? (then) : (else),th:text="${exp}?${b}:${c}"

th:if                    if

th:unless           else

<div th:if="${exp}">exp为true显示</div>
<div th:unless="${exp}">exp为false显示</div>

ex: <div th:if="${exp1} gt 0 and ${exp2} lt 10"> ... </div>   可写成   <div th:if="${exp1 gt 0} and ${exp2 lt 10}"> ... </div> ,此时将由OGNL进行解析,推荐属性放{ }中,运算放{ }外。

each、switch、selected

<tr th:each="user,userStat:${users}">
    <!-- userStat 记录循环状态,不写默认为user + Stat -->
    <td th:text="${user.name}"></td>
    <td th:switch="${user.gender}">
        <span th:case="0">男</span>
        <span th:case="1">女</span>
        <span th:case="*">其他</span><!-- 其他情况用 *  -->
    </td>
</tr>
<option th:selected="${exp} == xyz ">xx</option>

在js中取值:

<script th:inline="javascript">
    var size = [[${list.size }]]
<script>

标签上自定义属性值:   th:attr="属性名=属性值[,属性名=属性值]"

<div th:attr="tag=${oid},data-code=${ssqdCode}"></div>

 

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值