SpringBoot学习-模板引引擎之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
@ConfigurationProperties(
prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";

只需要把HTML页面放在classpath:/templates/,Thymeleaf就能自动渲染。

使用

  1. 导入thymeleaf的名称空间

    1
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
  2. 使用thymeleaf的语法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <h1>成功!</h1>
    <!--th:text 将div里面的文本内容设置为-->
    <div th:text="${hello}"></div>
    </body>
    </html>

语法

th:任意html属性

th:text改变当前元素里面的文本内容;

th:任意html属性;来替换原生属性的值

th:任意html属性

表达式

  1. Simple expressions:(表达式语法)

    • Variable Expressions: ${…} 获取变量值:OGNL

      • 1)、获取对象的属性、调用方法
      • 2)、使用内置的基本对象
        • #ctx : the context object.
        • #vars: the context variables.
        • #locale : the context locale.
        • #request : (only in Web Contexts) the HttpServletRequest object.
        • #response : (only in Web Contexts) the HttpServletResponse object.
        • #session : (only in Web Contexts) the HttpSession object.
        • #servletContext : (only in Web Contexts) the ServletContext object.
      • 3)、内置的工具对象
        • #execInfo : information about the template being processed.
        • #messages : methods for obtaining externalized messages inside variables expressions, in the same way as they
          would be obtained using #{…} syntax.
        • #uris : methods for escaping parts of URLs/URIs
          Page 20 of 106
        • #conversions : methods for executing the configured conversion service (if any).
        • #dates : methods for java.util.Date objects: formatting, component extraction, etc.
        • #calendars : analogous to #dates , but for java.util.Calendar objects.
        • #numbers : methods for formatting numeric objects.
        • #strings : methods for String objects: contains, startsWith, prepending/appending, etc.
        • #objects : methods for objects in general.
        • #bools : methods for boolean evaluation.
        • #arrays : methods for arrays.
        • #lists : methods for lists.
        • #sets : methods for sets.
        • #maps : methods for maps.
        • #aggregates : methods for creating aggregates on arrays or collections.
        • #ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
    • Selection Variable Expressions: *{…} 选择表达式:和${}在功能上是一样

      • 1)、补充:配合 th:object=”${session.user}”

        1
        2
        3
        4
        5
        <div th:object="${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>
    • Message Expressions: #{…} 获取国际化内容

    • Link URL Expressions: @{…} 定义URL

      1
      @{/order/process(execId=${execId},execType='FAST')}
    • Fragment Expressions: ~{…} 片段引用表达式

      1
      <div th:insert="~{commons :: main}">...</div>
  2. 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 ,…
  3. Text operations:(文本操作)

    • String concatenation: +
    • Literal substitutions: |The name is ${name}|
  4. Arithmetic operations:(数学运算)

    • Binary operators: + , - , * , / , %
    • Minus sign (unary operator): -
  5. Boolean operations:(布尔运算)

    • Binary operators: and , or
    • Boolean negation (unary operator): ! , not
  6. Comparisons and equality:(比较运算)

    • Comparators: > , < , >= , <= ( gt , lt , ge , le )
    • Equality operators: == , != ( eq , ne )
  7. Conditional operators:(条件运算(三元运算符))

    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)Default: (value) ?: (defaultvalue)
    • Default: (value) ?: (defaultvalue)
  8. Special tokens:(特殊操作)

    • Page 17 of 106No-Operation: _(不进行任何操作)

公共页面元素抽取

使用方式

  1. 抽取公共片段

    • 使用片段名:

      1
      2
      3
      <div th:fragment="copy">
      &copy; 2011 The Good Thymes Virtual Grocery
      </div>
    • 使用选择器:

      1
      2
      3
      <div id="copy-section">
      &copy; 2011 The Good Thymes Virtual Grocery
      </div>
  1. 引入公共片段

    • 使用选择器:

      1
      <div th:insert="~{footer :: #copy-section}"></div>
    • 使用片段名:

      1
      <div th:insert="~{footer :: copy}"></div>
    • 引入方式一:

      1
      <div th:insert="~{footer :: copy}"></div>
    • 引入方式二:省略~{}

      1
      <div th:insert="footer :: copy"></div>
  2. 语法

    • ~{templatename::selector} : 模板名::选择器
    • ~{templatename::fragmentname} : 模板名:片段名
  3. 效果

    • insert的功能片段在div标签中
    • 如果使用th:insert等属性进行引入,可以不用写~{};
    • 行内写法可以加上:[[~{}]];[(~{})]

三种引入公共片段的th属性

th:insert :将公共片段整个插入到声明引入的元素中

th:replace :将声明引入的元素替换为公共片段

th:include :将被引入的内容包含进声明引入的元素中

  1. 公共片段

    1
    2
    3
    <footer th:fragment="copy">
    &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
  2. 引入公共片段

    1
    2
    3
    <div th:insert="footer :: copy"></div>
    <div th:replace="footer :: copy"></div>
    <div th:include="footer :: copy"></div>
  3. 效果

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <div>
    <footer>
    &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
    </div>

    <footer>
    &copy; 2011 The Good Thymes Virtual Grocery
    </footer>

    <div>
    &copy; 2011 The Good Thymes Virtual Grocery
    </div>

引入片段传递参数

方式一:fragment使用形参接收参数

  1. 公共片段使用参数

    1
    2
    3
    <div th:fragment="frag (onevar,twovar)">
    <p th:text="${onevar} + ' - ' + ${twovar}">...</p>
    </div>
  2. 引入公共片段时传递参数

    • 方式一:onevar接收第一个值value1,twovar接收第二个值value2

      1
      <div th:replace="::frag (${value1},${value2})">...</div>
    • 方式二:形参名和传递的参数名相同,值传给对应的形参

      这种传递参数是可以没有顺序的:

      1
      <div th:replace="::frag (onevar=${value1},twovar=${value2})">...</div>

      等价于:

      1
      <div th:replace="::frag (twovar=${value2},onevar=${value1})">...</div>

方式二:fragment不使用变量名

  1. 公共片段使用参数

    1
    2
    3
    <div th:fragment="frag">
    <p th:text="${onevar} + ' - ' + ${twovar}">...</p>
    </div>
  2. 引入公共片段时传递参数

    1
    <div th:replace="::frag (onevar=${value1},twovar=${value2})">
  3. 注意:

    • 传递的参数和使用的时候调用的参数名必须一致
    • 传递的参数名不能重复

最后更新: 2020年07月29日 11:21

原始链接: http://ligangit.com/2020/07/27/SpringBoot学习-模板引引擎-thymeleaf/

× 请我吃糖~
打赏二维码