SpringBoot的Thymeleaf模板基本语法以及去掉H5规范

版权声明: https://blog.csdn.net/woshangniyixiao/article/details/89450246

  首先简单说说Themeleaf,这是个页面模板渲染引擎,如果你用过jsp,那肯定就不陌生了。thymeleaf和jsp的运行原理都差不多,都是系统去对页面进行渲染补充,最后展现的一个过程。所以如果你愿意,你的页面可以不叫xxxx.html,你可以叫xxx.page,xxxx.xxx,然后在propertites或者yml里配置好结尾即可。但是本质都是HTML页面而已,只不过需要稍微修饰一下。类似的模板语言还有很多,比如velocity等等。

  然后说一下这个配置。thymeleaf的配置有一个点就是关于它硬性要求H5规范。所以对于前段开发不是很熟悉的,或者项目改造来不及做大规模规范化修改的,需要将H5的规则限制成弱限制。配置如下:

pom.xml:

<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.22</version>
</dependency>

 然后在yml里配置

spring.thymeleaf.mode=LEGACYHTML5

这样就开启了H5不严格校验。

另外Thymeleaf的一些基本配置:

spring.themeleaf.prefix=classpath:/templates/    指定模板目录

spring.themeleaf.suffix= .html   指定结尾

spring.themeleaf.encoding=UTF8     字符集

spring.themeleaf.cache=true      开启页面缓存

接下来说语法:

post请求的写法:

@RequestMapping("/test")
public String messages(User user) {
     ...
    return "redirect:/post/path";   //跳转到path所在controller处理
}
<form th:action="@{/test}" th:object="${user}" th:method="post" >
    <input  type="text" th:filed="*{name}" />  //filed 见下方
    <input type="submit" />
</form>

 将值赋给js变量:

public String messages(Model model) {
    model.addAttribute("message", "hello");
    return "index";
    }
<script th:inline="javascript">
    var message = [[${message}]];
    console.log(message);
</script>

操作整个po对象:

<input th:id="${user.name}" th:name="${user.name}" th:value="${user.name}" />
//或者
<div th:object="${user}">
    <input  th:id="*{name}"   />
    <input  th:id="*{age}"   />
</div>

格式化时间显示:

 <input  th:id="*{#dates.format(mytime,'yyyy-MM-dd HH:mm:ss')}"   />

循环遍历集合:

<tr th:each="user:${users}">  //以user为基本单元
    <td th:text="${user.name}"></td>
    <td th:text="${user.age}"></td>
</tr>

引用yml的配置变量并且做筛选判断:

roles.properties文件:
roles.manage=b
roles.superadmin=c
<div th:switch="${user.name}">
    <p th:case=" 'a' "> 这是A </p>
    <p th:case="${roles.manage}"> 这是manage </p>
    <p th:case=" ${roles.superadmin} "> 这是admin </p>
     <p th:case="*"> 这是其他 </p>
</div>

文本和富文本:

<div  th:utext="${ha}"></div>  就是你写了 <a>标签,会显示成标签
<div  th:text="${ha}"></div> 就是你写了 标签但是显示成文本

filed变量:

 <input  type="text" th:filed="*{name}" /> 
 等同于
  <input  type="text" th:id="*{name}" th:name="*{name}" th:value="*{name}" /> 

判断:

<div  th:if="${user.age} == 18"  > 18</div>
<div  th:if="${user.age} gt 18"  > 18+</div>
<div  th:if="${user.age} lt 18"  > 18-</div>
<div  th:if="${user.age} ge 18"  > 18+=</div>
<div  th:if="${user.age} le 18"  > 18-+</div>
只显示符合条件的

选择:

<select> 
<option th:selectde="${user.name eq 'sss'}"> sss </option>
<option th:selectde="${user.name eq 'xxx'}"> sss </option>
</select>
会默认为sss

猜你喜欢

转载自blog.csdn.net/woshangniyixiao/article/details/89450246