前端模板引擎Thymeleaf的简单应用笔记

一. Thymeleaf的介绍.

Thymeleaf 是一个web端的并且独立的Java模板引擎,他能够处理HTML、XML、JavaScript、CSS以及纯文本,Thymeleaf的理念是创建一种优雅和易维护的模板,为了实现这一点,它建立在自然模板之上,将逻辑注入到模板文件中,还不会影响到模板被用作设计原型。Thymeleaf一开始就设计了Web标准,SpringBoot官方推荐使用Thymeleaf 而不是JSP。

JSP:
1.Jsp的本质是Servlet,就是一个.class,如果在jdk1.7以及之前,如果Jsp页面的数量足够多的话,会导致一个问题,项目无法启动.
JVM -> jdk1.6,jdk1.7,jdk1.8方法区的实现都是有所不同的.
2.Jsp页面可以嵌套Java代码的<% %> ,会破坏MVC模式,导致耦合过高.
3.Jsp页面需要引入一个jstl标签库才可以实现一些特有的功能.
4.SpringBoot默认不支持Jsp的.

Thymele:
1.SpringBoot默认支持Thymeleaf,并且主推Thymeleaf.
2.Thymeleaf是以html页面为模板的,只需要添加一个约束即可实现动态效果.
3.Thymeleaf提供了各种各样的表达式,让你可以在页面中疯狂的操作.
4.Thymeleaf可以让前端人员专门使用html做页面开发,并自己添加测试数据,之后交给后台人员,可有在不修改前端页面的前提下,动态填入数据.
直接打开html页面,有测试数据.
通过后台controller路径访问,有真实数据.

二. Thymeleaf的入门

#thymeleaf模板基本配置
spring:
  thymeleaf:
    mode: HTML5
    cache: false
    encoding: utf-8

1. 创建SpringBoot项目.

2. 导入依赖.

<dependencies>
<!--        thymeleaf启动器-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
<!--        web启动器-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

3. 查看Thymeleaf的配置信息.

在这里插入图片描述在这里插入图片描述

4. 编写Controller.

@Controller
public class IndexController {

    @GetMapping("/index")
    public String index(Model model){
    	model.addAttribute("info","SpringBoot Thymeleaf!!!");
        return "index";
    }
}

5. 尝试获取域中的数据.

在thymeleaf中获取request域中的数据.

三. Thymeleaf的$表达式

1. $ 表达式中可以添加的内容. (变量表达式)

Ps: 使用表达式时,一定要在 th:属性名=“表达式”

${}:
1. 可以直接填写域中数据的key,从而获取value.
2. 直接编写文本内容.

     字符串,数值,布尔,null

3.在${}中使用四则运算和取余操作也可以.

 	+ - & / %

4.关系运算符.

 	>  >= <  <= == != 
 	gt ge lt le eq ne

5.逻辑运算符

 	and or not !

6.三元运算符.

 	(条件表达式) ? 值1 : 值2

5.Thymeleaf提供了大量的内置对象,可以直接使用.

	${#具体的对象}
		Servlet中的对象: request,session,response.
		工具类: strings,lists,maps,dates....

2. Thymeleaf可以编写的属性.

标签自带的属性,Thymeleaf基本全部都支持.
直接书写style,不需要通过controller转发,即可正常看到样式.
书写 th:style ,需要通过controller转发到thymeleaf页面,style才会被页面正常的解析.
如果通过controller转发到页面,th:的属性会覆盖正常编写的属性.

<h1 style=""></h1>
<h1 th:style="${'color:red;'}" th:text="${#request.getContextPath()}">Thymeleaf!!</h1>

1.text与utext

	String text = "<a href='#'>点我有惊喜</a>";
    String utext = "<a href='#'>点我有惊喜</a>";
    model.addAttribute("text",text);
    model.addAttribute("utext",utext);
	<h1 th:text="${text}">Hello Thymeleaf!!</h1>   -> 不会解析内容,将其当做纯文本
	<h1 th:utext="${utext}">Hello Thymeleaf!!</h1>  -> 会解析内容中标签.

2.从域中取出一个对象时,如果将对象中的属性展示到页面.

public class User {

    private String name;
    private Integer age;
    private Date birthday;
    private String hobby;
}

更优雅的方式:

<ul th:object="${user}">
    <li th:text="*{name}"></li>
    <li th:text="*{getAge()}"></li>
    <li th:text="*{['birthday']}"></li>
    <li th:text="*{#dates.format(['birthday'],'yyyy-MM-dd HH:mm:ss')}"></li>
    <li th:text="*{hobby}"></li>
</ul>

方式2:

<ul>
    <li th:text="${user.name}"></li>			<!-- 推荐使用这种,更符合jsp用户的习惯 -->
    <li th:text="${user.getAge()}"></li>
    <li th:text="${user['birthday']}"></li>
    <li th:text="${#dates.format(user['birthday'],'yyyy-MM-dd HH:mm:ss')}"></li>
    <li th:text="${user.hobby}"></li>
</ul>

3.遍历一个集合并获取其中的全部对象并展示.

list

<!--    <c:forEach var="u" varStatus="uStatus" items="${list}"></c:forEach>-->
<table border="1px">

    <tr th:each="u , uStatus : ${list}">
        <td th:text="${uStatus.count}"></td>
        <td th:text="${u.name}"></td>
        <td th:text="${u.age}"></td>
        <td th:text="${#dates.format(u.birthday,'yyyy-MM-dd HH:mm:ss')}"></td>
        <td th:text="${u.hobby}"></td>
    </tr>
</table>

map

<tr th:each="u,uStatus:${userMap}">
	<td th:text="${u.key}"/>
	<td th:text="${u.value.name}"/>
</tr>

4.数据回显.
1. 文本内容回显.

<input th:value="${user.name}" th:name="name" th:id="name" />  <br />

<input th:field="${user.age}" /> <br />

2.时间类型回显. 无法使用field

<input type="datetime" th:value="${#dates.format(user.birthday,'yyyy-MM-dd HH:mm:ss')}" th:name="birthday" />

3.下拉列表回显.

<select name="hobby">
        <option th:selected="${user.hobby eq 'CTRL!'}">CTRL!</option>
        <option th:selected="${user.hobby eq '呵呵‘}">呵呵</option>
        <option th:selected="${user.hobby eq '哈哈'}">哈哈</option>
        <option th:selected="${user.hobby eq '嘿嘿嘿'}">嘿嘿嘿</option>
</select>

5.逻辑判断.
th:if=“boolean” th:if的表达式需为boolean值。如果为true,则标签显示,如果为false,则标签不显示。
th:unless=“boolean” th:unless和th:if相反,表达式也需为boolean值。如果为true,则标签不显示,如果为false,则标签显示

    <h1 th:if="${user.age ge 18}">已满18岁,可以进入,网吧</h1>

    <h1 th:unless="${user.age ge 18}">返回false展示当前标签内容</h1>
	<div th:switch="${user.age}">
        <h1 th:case="88">刚好88岁</h1>
        <h1 th:case="28">刚好28岁</h1>
        <h1 th:case="*">不是18岁,也不是28岁.</h1>
    </div>

6.绑定事件传参.

如果需要在绑定事件时,传递参数到函数中,需要使用到thymeleaf另一个语法来书写.

	<button type="button" th:onclick="del([[${user.age}]])"></button>

到了js中,也需要去域中获取值,在js中编写时,就需要先**[[ 内部写表达式 ]]**

四. Thymeleaf的路径处理,@ 表达式

书写请求路径:@{} -> 链接|路径表达式.

<script th:src="@{/jquery.min.js}" ></script>
<a th:href="@{/show}">访问controller方法</a>
<a th:href="@{/static_index.html}">访问静态页面</a>

使用@{}帮助我们在js代码中获取项目路径

	th:inline="javascript" 解析js代码中的thymeleaf关键字.[[]]
	th:inline="none" 不去解析js代码中的thymeleaf关键字.[[]]
	<script th:inline="javascript" >
	
		baseUrl = [[@{/}]];
	</script>

静态资源,统统放到resources下的static目录中,这个目录和传统的web项目的webapps目录一致

模板引擎,统统放到templates下,这个目录和传统的web项目的WEB-INF一样.
ps:如果在代码出错时,templates下有一error.html页面时,会自动跳转到这个页面中.

五. Thymeleaf的页面引入

创建footer.html文件用下面的内容替换

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<!--fragment : 设置名称,用于后面被其他页面依赖-->
	<footer th:fragment="companyInfo">
	<p>设为首页 SpringBoot 使用<span th:text="${projectName}"/>前必读 </p>
	</footer>

可以看到页面当中还存在一个变量projectName,这个变量的值可以在引入页面中通过 th:with=“projectName=百度” 进行传值引入页面中只需要添加如下代码即可
– 替换内容

<div th:include="@{/footer} :: companyInfo" th:with="projectName=UC"/>

– 替换全部

<div th:replace="@{/footer} :: companyInfo" th:with="projectName=UC"/>

~片段表达式.
Thymeleaf的片段表达式 ~{}
1. 声明片段.
单独创建一个thymeleaf页面.
声明具体的标签内容之后添加一个属性th:fragment=“片段名”

2.引用片段.
th:insert="~{页面名 :: 片段名}" 将整个片段插入到th:insert所在的标签体内.
th:replace="~{页面名 :: 片段名}" 将整个片段替换掉th:replace所在的标签.
th:include="~{页面名 :: 片段名}" 将片段中位于fragment属性标签体内的内容,插入到th:include所在的标签体内.

六.Thymeleaf中的#{}

#{}在html页面中引用外部文件中的内容. 一般使用#{}做国际化i18n.

1.在配置文件中配置

	spring:
	  messages:
		basename: messages

准备不同语言的文件.书写一下内容,文件默认命名要求为messages,先创建messges.properties并且放在resources目录下.
messages_zh.properties

            language.ch=中文
            language.en=英文
            username=用户名
            password=密码
            login=登录

messages_en.properties

			language.ch=Chinese
            language.en=English
            username=username
            password=password
            login=login

将idea中所有的编码格式设置为UTF-8
settings -> file encoding -> UTF-8
2 创建login.html,并编写内容.

		使用#{}引入上述.properties文件中的内容
		th:text="#{username}

3 转发到这个页面.
先编写一个配置文件,将需要使用到的SessionLocaleResolver对象注入到IOC容器中.

@Configuration
public class I18nConfig {
	@Bean
	public LocaleResolver localeResolver(){
    	return new SessionLocaleResolver();
	}
}

在页面的切换中英文的超链接位置添加href属性,并传递参数,指定中英文切换的信息.

<a th:text="#{language.ch}" th:href="@{/login-ui(i=0)}"></a>
<a th:text="#{language.en}" th:href="@{/login-ui(i=1)}"></a>

在转发到login页面前,通过SessionLocaleResolver对象.setLocale指定具体的语种.

@Controller
public class LoginController {

@Autowired
private LocaleResolver localeResolver;

@GetMapping("/login-ui")
public String loginUI(@RequestParam(defaultValue = "0") Integer i, HttpServletRequest request, HttpServletResponse response){
    if(i == 0){
        // 要求中文
        localeResolver.setLocale(request,response, Locale.CHINESE);
    }else{
        // 要求英文
        localeResolver.setLocale(request,response, Locale.ENGLISH);
    }
    return "login";
}

}
自动去找messages_??.properties文件中的内容.

注意

1、凡是涉及到thymeleaf模板语法的标签都必须加上thymeleaf模板特有的标志th:
2、SpringBoot在使用thymeleaf模板时,要注意标签闭合
3、在进行SpringBoot整合dubbo时,会出现在模板中使用JavaScript,带有;标识符的语法不能运行报错的问题(比如在thymeleaf模板的JavaScript标签中使用for(;;)循环语句),这时候可以使用外部导入js
文件的方式解决
4、尽量使用HTML5模板(配置文件需要配置),防止出现莫名其妙报错的问题

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值