spring boot 与 thymeleaf (3): 设置属性、条件、遍历、局部变量、优先级、内联语法

前面记录了 thymeleaf 基本表达式, 这里继续看一下其他功能.

一. 设置属性值

这里的controller, html框架 还是沿用上一篇的部分.

html:

<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">设置属性值</h3>
    </div>
    <div class="panel-body">
        <!--从自定义属性这里看, html所有的属性, 都可以通过 th:属性名=的方式来写-->
        <p th:elvin="${book.name}">1.自定义属性 th : elvin</p>

        <!--attr设置属性
        attr可以设置任何属性值, 但是一般不会用它设置所有属性值-->
        <p th:attr="elvin=${book.name},title=${book.name}">2.attr设置属性值</p>

        <!--一般html原来的属性, 通过 th : 属性名 的方式来使用
        设置多个属性: th : alt-title, th : lang-xmllang -->
        <p th:title="${book1.name}">3.html原来的属性</p>
        <!--对于checked, disabled 这种的, 其判断值的方式和 if 的方式一致, 具体在if中详述 -->
        <input type="checkbox" th:checked="${book.price % 2 == 0}" th:disabled="${book.price % 2 == 0}" />a
        <input type="checkbox" th:checked="1" th:disabled="${book.price % 2 gt 0}" />b
        <input type="checkbox" th:checked="no" />c

        <!--classappend:可以添加class,而不会删除之前的class
        styleappend:可以添加样式,不会删除之前的样式,但是效果上会覆盖之前的样式-->
        <p class="pc" th:classappend="cp" style="border: 1px solid blue;background-color:red;"
           th:styleappend="‘background-color:#82af86;‘">4.追加class和style</p>

        <!--attrappend:在原有基础的后面添加属性值
        attrprepend:在原有的基础的前面插入属性值-->
        <p title="原来的title" th:attrappend="title=‘ 添加的title‘" th:attrprepend="title=‘最前面的title ‘">5.前置,后置添加属性值</p>

        <!--虽然这里提供了事件设置的方式, 但是个人建议, 将事件绑定分离出去-->
        <p th:onclick="|console.log(‘${book.publishTime}‘)|">6.设置事件属性</p>

    </div>
</div>

结果展示:

二. 条件运算

<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">条件运算</h3>
    </div>
    <div class="panel-body">
        <!--
           这里的 if判断 作用有点类似javscript里面的if
           判断通过的条件:
               1.表达式的值不为null
               2.如果为布尔值, 且为true : th:if="true"
               3.不为0的数字, 负数也判定通过
               4.不为‘0‘的字符
               5.不为:"false","off","no"的字符串
       -->
        <!--这里的if unless 其实就相当于是 if else-->
        <p th:if="${book.price > 10000}" th:text="|本书单价为:${book.price / 100}元, 有点小贵|"></p>
        <p th:unless="${book.price > 10000}" th:text="|本书单价为:${book.price / 100}元, 价格可以接受|"></p>

        <p th:switch="${book.price}">
            <span th:case="100" th:text="1块钱"></span>
            <span th:case="${book.price}" th:text="${book.price / 100} + ‘元‘"></span>
            <span th:case="*" th:text="居然都不是, 只能选这个了"></span>
        </p>
    </div>
</div>

if 和 unless 是相反的, 所以如果只有一个 if , unless确实可以当成是if对应的else来使用. 当然, 如果是 if - else if - else if - else也是可以实现的, 但是要嵌套进去, 不方便阅读. 就不写了.

switch里面, case="*" 相当于java里面的default, 只要有一个满足条件, 别的都不会再显示和判断了.

结果展示:

三. 遍历

数据准备: 在原来controller的方法下面继续添加

List<Book> bookList = new ArrayList<>();
bookList.add(book);
bookList.add(book1);
bookList.add(new Book("bootstrap", new DateTime().toString("yyyy-MM-dd"), 11000L));
bookList.add(new Book("javascript", new DateTime().toString("yyyy-MM-dd"), 1020L));

model.addAttribute("bookList", bookList);

Map<String, Book> map = new HashMap<>();
String pre = "index_";

for (int i = 0; i < bookList.size(); i++) {
    map.put(pre + i, bookList.get(i));
}

model.addAttribute("bookMap", map);

html:

<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">列表List</h3>
    </div>
    <div class="panel-body">
        <ul class="list-group">
            <!--循环方法
                这里的item,自命名的,就相当于 bookList.get(index)
                iterInfo,自命名的, 是单条数据的补充信息, 比如里面有 索引。
                each可以迭代的对象:
                    1. 任何实现java.util.Iterable接口的对象
                    2. 任何实现java.util.Enumeration接口的对象
                    3. 任何实现java.util.Iterator接口的对象, 其值将被迭代器返回,而不需要再内存中缓存所有值
                    4. 任何实现java.util.Map的接口对象. 迭代时, iter变量将是 Entry类
                    5. 任何数组
                    6. 任何其将被视为包含对象本身的单值列表
            -->
            <li class="list-group-item" th:each="item,iterInfo:${bookList}">
                <span th:text="‘index:‘ + ${iterInfo.index}"></span>
                <span th:text="‘size:‘ + ${iterInfo.size}" style="margin-left:10px;"></span>
                <span th:text="‘count:‘ + ${iterInfo.count}" style="margin-left:10px;"></span>
                <span th:text="‘odd:‘ + ${iterInfo.odd}" style="margin-left:10px;"></span>
                <span th:text="‘even:‘ + ${iterInfo.even}" style="margin-left:10px;"></span>
                <span th:text="‘first item:‘ + ${iterInfo.first}" style="margin-left:10px;"></span>
                <span th:text="‘last item:‘ + ${iterInfo.last}" style="margin-left:10px;"></span>
                <span th:text="${item.name}" style="margin-left:10px;"></span>
                <span th:text="${item.price} + ‘分‘" style="margin-left:10px;"></span>
                <span th:text="${item.publishTime}" style="margin-left:10px;"></span>
            </li>
        </ul>
    </div>
</div>

<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">列表Map</h3>
    </div>
    <div class="panel-body">
        <ul class="list-group">
            <!--循环方法
                这里的item,自命名的,就相当于 bookList.get(index)
                iterInfo,自命名的, 是单条数据的补充信息, 比如里面有 索引。
                each可以迭代集合, 数组, Map(iter变量将是 Entry 类)
            -->
            <li class="list-group-item" th:each="item,iterInfo:${bookMap}">
                <span th:text="‘index:‘ + ${iterInfo.index}"></span>
                <span th:text="‘size:‘ + ${iterInfo.size}" style="margin-left:10px;"></span>
                <span th:text="‘count:‘ + ${iterInfo.count}" style="margin-left:10px;"></span>
                <span th:text="‘odd:‘ + ${iterInfo.odd}" style="margin-left:10px;"></span>
                <span th:text="‘even:‘ + ${iterInfo.even}" style="margin-left:10px;"></span>
                <span th:text="‘first item:‘ + ${iterInfo.first}" style="margin-left:10px;"></span>
                <span th:text="‘last item:‘ + ${iterInfo.last}" style="margin-left:10px;"></span>

                <span th:text="${item.key}" style="margin-left:10px;"></span>
                <span th:text="${item.value.name}" style="margin-left:10px;"></span>
                <span th:text="${item.value.price} + ‘分‘" style="margin-left:10px;"></span>
                <span th:text="${item.value.publishTime}" style="margin-left:10px;"></span>
            </li>
        </ul>
    </div>
</div>

结果展示:

四. 局部变量

在each中,  item:${list}, 这个item, 其实就是一个局部变量.

但是如果要定义自己的局部变量, 怎么操作呢.

<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">局部变量</h3>
    </div>
    <div class="panel-body">
        <!--1. 先来个简单的-->
        <p th:with="first=‘123abc‘" th:text="${first}"></p>
        <!--2. 这里two在前面, 如果从前往后, 肯定会报错, 这里能正常显示, 说明标签间有优先级-->
        <p th:text="${two.name}" th:with="two=${book}"></p>
        <!--3.多个变量的时候-->
        <p th:with="name=${book.name}, price=${book.price}" th:text="|${name} : ${price}|"></p>
    </div>
</div>

结果展示:

五. 优先级

在上一part中, 发现了, 在同一个tag中, th:with 和 th:text 的顺序并不影响解析结果. 这肯定是有一个优先级顺序在里面

优先级从上往下, 逐渐变小

Order Feature Attributes
1 Fragment inclusion th:insert   th:replace
2 Fragment iteration th:each
3 Conditional evaluation
th:if   th:unless

th:switch  th:case

4 Local variable definition th:object  th:with
5 General attribute modification th:attr   th:attrprepend  th:attrappend
6 Specific attribute modification th:value  th:href  th:src ...
7 Text(tag body modification) th:text   th:utext
8 Fragment specification th:fragment
9 Fragment removal th:remove

六. th:remove

这里remove没有出现过, 正好在这里就看一下, remove 具体是要删除什么

<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">remove</h3>
    </div>
    <div class="panel-body">
        <ul class="list-group" th:msg="all" th:remove="all">
            <li>all-1</li>
            <li>all-2</li>
        </ul>
        <ul class="list-group" th:msg="body" th:remove="body">
            <li>body-1</li>
            <li>body-2</li>
        </ul>
        <div class="list-group" th:msg="tag" th:remove="tag">
            <ul>
                <li>tag-1</li>
                <li>tag-2</li>
            </ul>
        </div>
        <div class="list-group" th:msg="all-but-first" th:remove="all-but-first">
            <p>all-but-first-1</p>
            <p>all-but-first-2</p>
        </div>

        <div class="list-group" th:msg="none" th:remove="none">
            <p>none-1</p>
            <p>none-2</p>
        </div>
    </div>
</div>

结果展示:

all: 将所有的都删除掉了, 仿佛没有出现过

body: 删除标签内部的内容

tag: 删除标签, 但是保留子项

all-but-first: 删除除第一个以外的所有后代

none: 什么都不做

七. 内联语法

其实这个在上一篇已经出现过. 内联语法, 主要是在模板中, 或者css, js中使用.

thymeleaf除了可以通过标签来使用变量, 还可通过[[${...}]]的方式来使用.

1. 在css中, 想要使用变量

 <style th:inline="css">
        /*通过[ [ $ { }]]的方式访问model中的属性*/
        .bgcolor {
            background-color: [[${color}]]
        }
 </style>

2. 在js中, 使用

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

3. 在html中使用

  <p th:inline="text">买了一本书:[[${book.name}]], 花了[[${book.price/100}]]块钱</p>

不建议在标签内容里面这么写, 当然, 不利于原型的展示.

4. 禁用[[${...}]]

<p th:inline="none">买了一本书:[[${book.name}]], 花了[[${book.price/100}]]块钱</p>

Demo:

<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">内联语法</h3>
    </div>
    <div class="panel-body">
        <!--1. css中使用-->
        <style th:inline="css">
            .color{
                background-color: [[${color}]];
            }
        </style>

        <!--2. html 标签内部使用-->
        <p th:inline="text" class="color">买了一本书:[[${book.name}]], 花了[[${book.price/100}]]块钱</p>

        <!--3. html标签内部禁用-->
        <p th:inline="none">买了一本书:[[${book.name}]], 花了[[${book.price/100}]]块钱</p>

        <!--4. javascript中使用-->
        <script th:inline="javascript">
            var book = [[${book1}]];
            console.log(book);

            [# th:each="item:${bookList}"]
                console.log([[${item}]]);
            [/]
        </script>
    </div>
</div>

结果展示:

这里有个 [# ] [/] , 可以当成是 标签 来用. 是thymeleaf提供的

时间: 2024-08-30 05:27:24

spring boot 与 thymeleaf (3): 设置属性、条件、遍历、局部变量、优先级、内联语法的相关文章

Spring Boot + MyBatis + Thymeleaf实现简单留言板应用

Spring Boot + MyBatis + Thymeleaf实现简单留言板应用 本项目主要介绍使用Spring Boot + MyBatis + Thymeleaf + Bootstrap来实现一个简单的增删改查(CRUD)留言板应用.高阶人士可以直接跳过. 源代码:https://github.com/qingwenwei/spring-boot-crud-example 功能介绍 发表帖子.帖子列表 编辑帖子 使用Spring Initializr构建项目 Spring Initial

Spring Boot 揭秘与实战(五) 服务器篇 - 其他内嵌服务器 发表于 2017-01-03 | Spring框架 | Spri

文章目录 1. Jetty 的切换 2. Undertow的使用 Spring Boot 可选择内嵌 Tomcat.Jetty 和 Undertow,因此我们不需要以 war 包形式部署项目.<Spring Boot 揭秘与实战(五) 服务器篇 - 内嵌的服务器 Tomcat剖析>一文,已经讲解了内嵌的服务器 Tomcat,那么,这篇文章大概讲解下另外两个内嵌的服务器 Jetty 和 Undertow. Jetty 的切换 Spring Boot 默认使用的是 Tomcat 作为内嵌的服务器,

spring boot:thymeleaf使用详解

简单说, Thymeleaf 是一个跟 Velocity.FreeMarker 类似的模板引擎,它可以完全替代 JSP .相较与其他的模板引擎,它有如下三个极吸引人的特点: 1.Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果.这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式.浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板

spring boot 与 thymeleaf (1): 国际化

在thymeleaf 里面有个消息表达式: #{...} , 可以借此来实现国际化. 在我使用这个功能的时候, 碰到了一个问题, 按照 JavaEE开发的颠覆者 Spring Boot实战  上面编码的时候, 出现了以下问题, 相信很多人都碰到过. ??home.welcome_zh_CN?? 这里推荐一篇博客, 里面有解决办法. 玩转spring boot--国际化 我也想将我自己代码记录下来. 一. 目录预览 这里我并没有按照资料上所述的, 将properties文件建在 index.htm

Spring Boot:Thymeleaf篇

Spring Boot干货系列:(四)Thymeleaf篇http://www.cnblogs.com/zheting/p/6707037.html 前言 Web开发是我们平时开发中至关重要的,这里就来介绍一下Spring Boot对Web开发的支持. 正文 Spring Boot提供了spring-boot-starter-web为Web开发予以支持,spring-boot-starter-web为我们提供了嵌入的Tomcat以及Spring MVC的依赖. 项目结构推荐 一个好的项目结构会让

Spring Boot? 使用Thymeleaf模板引擎渲染web视图

静态资源访问 在我们开发Web应用的时候,需要引用大量的js.css.图片等静态资源. 默认配置 Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则: /static /public /resources /META-INF/resources 举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件.启动程序后,尝试访问http://localhost:8080/D.jpg.如能显示图片,配置成功. 渲染

Spring Boot使用thymeleaf模板

Thymeleaf是个XML/XHTML/HTML5模板引擎,可以用于Web与非Web应用.Thymeleaf的主要目标在于提供一种可被浏览器正确显示的.格式良好的模板创建方式,因此也可以用作静态建模.可以完全替代JSP. Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果.这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式.浏览器解释 html 时会忽略未定

Spring Boot 环境变量读取 和 属性对象的绑定

凡是被Spring管理的类,实现接口 EnvironmentAware 重写方法 setEnvironment 可以在工程启动时,获取到系统环境变量和application配置文件中的变量. 如: @Configuration public class MyWebAppConfigurer implements EnvironmentAware { private static final Logger logger = LoggerFactory.getLogger(MyWebAppConfi

十五、Spring Boot 环境变量读取 和 属性对象的绑定

凡是被spring管理的类,实现接口 EnvironmentAware 重写方法 setEnvironment 可以在工程启动时,获取到系统环境变量和application配置文件中的变量. 如: @Configuration public class MyWebAppConfigurer implements EnvironmentAware { private static final Logger logger = LoggerFactory.getLogger(MyWebAppConfi