学习笔记——Spring Boot(4)

thymeleaf的用法和语法

      学习spring boot以后,如果打算进行web开发,则thymeleaf是一定要去学的(springboot推荐)。而thymeleaf到底是什么,我找了个资料:

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用

 

首先我们就要引入thymeleaf的依赖:

<!--导入thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

 

该版本是2.1版本的thymeleaf,如果要导入3以上的版本,则可以查看spring boot的官方文档:

<properties>
    <!--布局功能的支持程序-->
    <!--thymeleaf版本为3.0.0-->
    <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
    <!--layout版本为2.0.0-->
    <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
</properties>

 

  此时项目已经导入了thymeleaf了,而这时候我们只需要把我们所需要的HTML页面放在classpath:/template/的目录下,即:

thymeleaf就会帮忙自动渲染页面。

例如,我们在controller中加入:

@RequestMapping("/hello")

public Map success(Map<String,Object> map){

    map.put("hello","你好");

    return map;

}

 

 

下面就来说thymeleaf的语法,而在开始之前,先推荐两个学习thymeleaf的语法的网站:

  1. thymeleaf官方文档
  2. 纯洁的微笑的博客

 

首先,在导入新的html页面后,一定要导入thymeleaf的语法提示

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

导入以后你编写代码时才会有提示。

 

再来说说th:text这类结构的语法:

th:任意html属性(是来代替原本属性的值)

                                                                        (图片来源纯洁的微笑中博客)

 

                                                                    (图片来自官方文档第10节)

 

注:其中th:text和th:utext两种文本替换的方式,而它们是可以在<></>中使用 [[…]]和[(…)] 分别替代

 

 

而thymeleaf重要的还有表达式语法(可查看官方文档第4):

1)${…}

  变量表达式,可以获取变量值,对象的属性,调用对象的方法。除此之外,还有可以使用内置的基本对象和工具对象。

 

2)*{…}

  选择表达式,与变量表达式类似,可以预先选择对象来代替上下文变量。

 

3)#{…}

  国际化表达式,允许我们从一个外部文件(.properties)中获取区域文字信息

 

4)@{…}

   URL表达式,可以将有用的上下文或回话信息添加到URL,还可以添加相对路径,最重要的是可以设置参数:

@{/order/details(id=${orderId})}

 

5)~{…}

   片段引用表达式。

 

而在表达式中可以使用的有:

字面(Literals

  • 文本文字(Text literals): 'one text', 'Another one!',…
  • 数字文本(Number literals): 0, 34, 3.0, 12.3,…
  • 布尔文本(Boolean literals): true, false
  • 空(Null literal): null
  • 文字标记(Literal tokens): one, sometext, main,…

文本操作(Text operations

  • 字符串连接(String concatenation): +
  • 文本替换(Literal substitutions): |The name is ${name}|

算术运算(Arithmetic operations

  • 二元运算符(Binary operators): +, -, *, /, %
  • 减号(单目运算符)Minus sign (unary operator): -

布尔操作(Boolean operations

  • 二元运算符(Binary operators):and, or
  • 布尔否定(一元运算符)Boolean negation (unary operator):!, not

比较和等价(Comparisons and equality)

  • 比较(Comparators): >, <, >=, <= (gt, lt, ge, le)
  • 等值运算符(Equality operators):==, != (eq, ne)

条件运算符(Conditional operators

  • If-then: (if) ? (then)
  • If-then-else: (if) ? (then) : (else)
  • Default: (value) ?: (defaultvalue)

猜你喜欢

转载自blog.csdn.net/nanshenjiang/article/details/81369089
今日推荐