thymeleaf 模板引擎

Thymeleaf 模板引擎

  • Spring Boot 中推荐使用Thymeleaf 作为模板引擎。
  • Spring Boot 为Thymeleaf 提供的stater pom是spring-boot-starter-thymeleaf。(创建项目时可以直接添加Thymeleaf )
Thymeleaf 基础知识
  • Thymeleaf 是一个Java类库,是xml/xhtml/html 5 的模板引擎,可作为MVC的Web应用的View层。还提供了额外的模块与SpringMVC集成,可以完全替代JSP。

  • application.properties 配置文件中以spring.thymeleaf 开头来配置相关属性。

  • 引入thymeleaf :

    <html xmlns:th="http://www.thymeleaf.org">
    

    引入thymeleaf ,并将进行动态处理的元素将使用th:为前缀。

  • 引用Web静态资源:

    <link th:href="@{bootstrap-3.4.1-dist/css/bootstrap.min.css}"
    	rel="stylesheet">
    <link th:href="@{bootstrap-3.4.1-dist/css/bootstrap-theme.min.css}"
    	rel="stylesheet">
    	
    <script th:src="@{jquery-3.2.1.min.js}" type="text/javascript"></script>
    <script th:src="@{bootstrap-3.4.1-dist/js/bootstrap.min.js}"></script>
    

    通过@{}:引用Web资源。

  • 访问model中的数据:

    <span th:text="${singlePerson.name}"></span>
    

    通过${}:引用属性数据;注意th::前缀。

  • model中的数据迭代:

    <ul class="list-group">
    	<li class="list-group-item" th:each="person:${people}">
    		<span th:text="${person.name}"></span>
    		<span th:text="${person.age}"></span>
    	</li>
    </ul>
    

    通过th:each:来做循环。

  • 数据判断:

    <div th:if="${not #lists.isEmpty(people)}">
    

    通过th:if="${not #lists.isEmpty(people)}":判断people是否为空。Thymeleaf 支持><>=<===!=作为比较条件。

  • 在JavaScript中访问model:

    <script th:inline="javascript">
    	var single=[[${singlePerson}]];
    	console.log(single.name+"/"+single.age);
    	function getName(name){
    		console.log(name);
    	}
    </script>
    

    通过th:inline=“javascript”:添加到script标签,这样JavaScript代码即可访问model中的属性;

    通过[[${}]]:格式获得实际的值。

    <button class="btn" th:onclick="getName([[${person.name}]])">获得名字</button>
    

    注意格式:th:οnclick=“getName([[${person.name}]])”

    更多thymeleaf 常用标签见慕课网spring boot 6-3
    完整见thymeleaf 官方文档

其他模板引擎

  • freemarker、Groovy、Mustache、Velocity(1.4版本之后弃用,Spring Framework 4.3之后弃用)
  • jsp 模板引擎尽量避免使用:
    1. jsp只能打包为war 格式,不支持jar 格式,只能在标准的容器里跑(tomcat、jetty都可以);
    2. 内嵌的Jetty目前并不支持JSP;
    3. Undertow 不支持jsp;
    4. jsp自定义错误页面不能覆盖spring boot 默认的错误页面。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值