avatar

03.Thymeleaf语法

一、引入Thymeleaf

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

二、Thymeleaf的自动配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@Configuration
@EnableConfigurationProperties(ThymeleafProperties.class) //为ThymeleafProperties类绑定配置文件
@ConditionalOnClass(TemplateMode.class) //classPath存在这个类才生效
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {

@Configuration
@ConditionalOnMissingBean(name = "defaultTemplateResolver")//在容器中不存在defaultTemplateResolver才生效
static class DefaultTemplateResolverConfiguration {

private static final Log logger = LogFactory
.getLog(DefaultTemplateResolverConfiguration.class);

private final ThymeleafProperties properties;

private final ApplicationContext applicationContext;

DefaultTemplateResolverConfiguration(ThymeleafProperties properties,
ApplicationContext applicationContext) {
this.properties = properties;
this.applicationContext = applicationContext;
}

@Bean
public SpringResourceTemplateResolver defaultTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(this.applicationContext);
resolver.setPrefix(this.properties.getPrefix());//设置前缀
resolver.setSuffix(this.properties.getSuffix());//设置后缀
resolver.setTemplateMode(this.properties.getMode());
if (this.properties.getEncoding() != null) {
resolver.setCharacterEncoding(this.properties.getEncoding().name());
}
resolver.setCacheable(this.properties.isCache());
Integer order = this.properties.getTemplateResolverOrder();
if (order != null) {
resolver.setOrder(order);
}
resolver.setCheckExistence(this.properties.isCheckTemplate());
return resolver;
}

}
}

​ 可以看到,他创建了一个defaultTemplateResolver。他的默认前缀是classpath:/templates/ ,默认后缀是.html 也就是说,我们只要把html文件放到classpath:/templates/下,他就可以自动渲染。

三、Thymeleaf语法

  1. Thymeleaf的名称空间:

    1
    <html xmlns:th="http://www.thymeleaf.org">
  2. 简单的例子

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <!DOCTYPE html>
    <html lang="cn" xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="UTF-8">
    <title>第一个Thymeleaf</title>
    </head>
    <body>
    <p th:text="Hello">hi</p> <!- th:text里面的内容会替换掉本身的内容,如果不通过视图渲染,页面显示的内容就是hi -->
    </body>
    </html>
  3. 语法规则

    1. 文本替换

      • th:text :改变当前元素的文本内容。
      • 在Thymeleaf中,只要是th:html属性,都是可以替换原生的属性值
    2. 访问对象

      • Variable Expressions(变量表达式) : ${…}

        • ${}可以获取对象的属性、调用方法
        • 使用内置的基本对象
      • Selection Variable Expressions(选择表达式,和${}在功能上是一样的) : *{…}

        • 选择表达式如果没有选定对象,则功能和${}是一样的。而如果有选定对象,那么选择表达式是作用于选定对象的,而不是整个上下文对象。

        • 选定对象:使用th:object标明的就是选定对象。例如

          1
          2
          3
          4
          5
          <div th:object="${session.user}"> //${session.user}就是选定对象
          <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
          <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
          <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
          </div>

          上面代码,完全等同于下面的

          1
          2
          3
          4
          5
          <div>
          <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
          <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
          <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
          </div>
        • ${}和*{}是可以混用的。如下:

          1
          2
          3
          4
          5
          <div th:object="${session.user}">
          <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
          <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
          <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
          </div>
        • 当选定对象定义后,选择的对象也可以使用#object表达式的方式应用于${},如下:

          1
          2
          3
          4
          5
          <div th:object="${session.user}">
          <p>Name: <span th:text="${#object.firstName}">Sebastian</span>.</p>
          <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
          <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
          </div>
        • 当没有定义选定对象时,*{}和${}是一样的

          1
          2
          3
          4
          5
          <div>
          <p>Name: <span th:text="*{session.user.name}">Sebastian</span>.</p>
          <p>Surname: <span th:text="*{session.user.surname}">Pepper</span>.</p>
          <p>Nationality: <span th:text="*{session.user.nationality}">Saturn</span>.</p>
          </div>
      • Message Expressions: #{…}

        • 获取国际化内容
      • Link URL Expressions(超链接表达式): @{…}

        • th:href是⼀个修饰符属性:⼀旦处理,它将计算要使⽤的链接URL,并将该值设置为<a>标签的href属性。
        • 可以在@{}中执行表达式运算
        • 如果是需要传递参数,则在链接后面加上() ,如果有多个参数,使用, 分割。例如:@{/abc( a=${emp.id}, b='tst' )}
        • / 开头为相对路径。将会从应用上下文开始
      • Fragment Expressions: ~{…}

        • 片段引用表达式
    3. 常用th:属性

      常用th:属性

  4. Thymeleaf支持的变量及运算

    • 字面量
      • ext 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 ,…
    • 运算
      • 文本操作
        • 字符串连接:+
        • 字符串替换:|The name is ${name}|
      • 数学运算
        • 基本运算:+、—、*、/、%
        • 负号:-
      • 布尔运算
        • 二元运算: and,or
        • 布尔否定:not,!
      • 比较运算
        • 比较运算符:> , < , >= , <= ( gt , lt , ge , le )
        • 等号运算符: == , != ( eq , ne )
      • 条件运算(三元运算)
        • if-then:(if) ? (then)
        • If‐then‐else: (if) ? (then) : (else)
        • Default: (value) ?: (defaultvalue)
      • 特殊特征符
        • 无操作:_
    • 内置基本对象
      • 上下文对象:#ctx
      • 上下文变量:#vars
      • 上下文区域设置:#locale
      • (仅在Web Contexts中)HttpServletRequest对象:#request
      • 仅在Web上下⽂中)HttpServletResponse对象:#response
      • (仅在Web上下⽂中)HttpSession对象 :#session
      • (仅在Web上下⽂中)ServletContext对象:#servletContext
    • 内置工具对象
      • #execInfo:有关正在处理的模板的信息。
      • #messages:用于在变量表达式中获取外部化消息的方法法,与使#{…}语法获得的方式相同。
      • #uris:转义URL / URI部分的⽅法
      • #conversions:执行配置的转换服务(如果有的话)的方法。
      • #dates:java.util.Date对象的⽅法:格式化,组件提取等
      • #calendars:类似于#dates,但对于java.util.Calendar对象。
      • #numbers:用于格式化数字对象的方法。
      • #strings:String对象的⽅法:contains,startsWith,prepending ,appending等
      • #objects:一般对象的方法。
      • #bools:布尔的方法。
      • #arrays:数组的方法
      • #lists:列表的方法。
      • #sets:集合的方法。
      • #maps:地图方法。
      • #aggregates:在数组或集合上创建聚合的方法。
      • #ids:处理可能重复的id属性的方法(例如,作为迭代的结果)。

评论