当前位置: 代码迷 >> 综合 >> SpringBoot:thymeleaf-模板引擎
  详细解决方案

SpringBoot:thymeleaf-模板引擎

热度:113   发布时间:2023-09-18 15:53:07.0

1.模板引擎

JSP、Velocity、Freemarker、Thymeleaf;

它们的作用是把html(模板)中的动态的数据标识和后台程序中对应的数据内容匹配起来,渲染在模板页面上。

SpringBoot推荐的是Thymeleaf模板引擎,语法更简单,功能更强大。

2.Thymeleaf

2.1 引入

SpringBoot引入:

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

如果要切换版本,在properties标签里改,自己百度下格式就好。

2.2 使用

SpringBoot提供了Thymeleaf的自动配置,包括了关于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文件夹下。所以我们只要把html页面反正类路径下的templates文件夹下,就能够自动地对其进行thymeleaf渲染。

与此同时,配置了thymeleaf之后,SpringBoot框架将能够解析templates下的静态资源文件。但不影响SpringBoot的默认的静态资源文件夹的访问,可以同时进行。被thymeleaf动态渲染的页面只能在templates文件夹下,且不能用GET请求直接访问,必须转发才能访问。GET请求只能访问默认静态文件夹根目录的文件,要访问默认静态文件夹下文件夹里的文件必须用POST请求转发,在themeleaf框架下,templates文件夹也是默认静态文件根目录,如果它下面还有文件夹,也许要用POST请求才可以访问。

https://www.thymeleaf.org/documentation.html,可以在这里找到thymeleaf的官方文档,引导使用,举例:

1).首先要在html页面的html标签里引入thymeleaf的语法支持:“xmlns:th = "http://www.thymeleaf.org"”;

2).th:属性名 = "${hello}",表示将该元素的某个属性名设置为指定的值。${}中的参数是用map或者model放入session域中的关键字,用它来取出对应的数据值,即我们指定的值。

2.3 语法

1).th关键字可以修改任意的html元素的属性。

在官方文档中,我们对语法使用进行截图:

SpringBoot:thymeleaf-模板引擎
Attribute Precedence

2).标准表达式语法

Simple expressions:(表达式语法)Variable Expressions: ${...}    //获取表达式,OGNL。//1.获取对象的属性//2.使用OGNL内置的基本对象/*  #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#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: *{...}//和${}的功能是一样的,但有个补充功能如下:/*<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>配合th:object一起使用,可以用*号来指代刚刚创建的那个对象*/Message Expressions: #{...}    //获取国际化内容Link URL Expressions: @{...}    //定义url链接/*    <!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) --><a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a><!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) --><a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a><!-- Will produce '/gtvg/order/3/details' (plus rewriting) --><a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>*/Fragment Expressions: ~{...}    //插入文档
Literals(字面量)Text literals: 'one text', 'Another one!',…Number literals: 0, 34, 3.0, 12.3,…Boolean literals: true, falseNull literal: nullLiteral 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, orBoolean 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)
Special tokens:No-Operation: _ (不做任何操作的特殊字符)