Thymeleaf基础知识

以下一切均基于《Spring Boot 实战》一书

Thymeleaf是一个Java类库,它是一个xml/xhtml/html5的模板引擎,可以作为MVC的Web应用的view层。

Thymeleaf还提供了额外的模块与Spring MVC集成,所以我们可以使用Thymeleaf完全替代JSP。

下面将列举几种常用的用法

1.引入Thymeleaf

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

<head>
    <meta content="text/html;charset=UTF-8">
    <link th:src="@{bootstrap/css/bootstrap.min.css}" ref="stylesheet"/>
    <link th:src="@{bootstrap/css/bootstrap-theme.min.css}" ref="stylesheet"/>

    <body>
    <script th:src="@{jquery-1.10.2.min.js}"type="text/javascript" />
    <script th:src="@{bootstrap/js/bootstrap.min.js}" />
    </body>
</head>

通过xmlns:th=”http://www.thymeleaf.org”命名空间,将镜头页面转换为动态的视图。需要进行动态处理的元素将使用 th 为前缀
通过“”@{}“”引用web资源

2.访问model中的属性

<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">访问model</h3>
    </div>
    <div class="panel-body">
        <span th:text="${singlePerson.name}" />
    </div>
</div>

使用访问model中singlePerson的name属性,动态内容需要添加th

3.model中的数据迭代

Thymeleaf的迭代和JSP的写法也很相似,代码如下:

<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">列表</h3>
    </div>
    <div class="panel-body">
        <ul class="list-group">
            <li class="list-group-item" th:each="person:${people}">
                <span th:text="${person.name}" />
                <span th:text="${person.age}" />
            </li>
        </ul>
    </div>
</div>

使用th:each=”person:${people}”来进行迭代,person作为迭代元素来使用

4.数据判断

<div th:if="${not #lists.isEmpty(people)}">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">列表</h3>
        </div>
        <div class="panel-body">
            <li class="list-group-item" th:each="person:${people}">
                <span th:text="${person.name}" />
                <span th:text="${person.age}" />
            </li>
        </div>
    </div>
</div>

通过th:if=”${not #lists.isEmpty(people)}”表达式判断people是否为空

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值