模板引擎Thymeleaf的简单了解

模板引擎

SpringBoot中,项目以jar包的形式打包,而不是web项目,而且使用的tomcat是嵌入式的tomcat,故不支持JSP了

模板引擎:JSP、Velocity、Freemarker、Thymeleaf

SpringBoot推荐的Thymeleaf;

语法更简单,功能更强大;

1、引入thymeleaf;

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
上面引入的版本默认是2.1.6,切换thymeleaf3版本,在properties标签下加入2个标签
<properties>
        <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
        <!-- 布局功能的支持程序  thymeleaf3主程序  layout2以上版本 -->
        <!-- thymeleaf2   layout1-->
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
  </properties>

2、Thymeleaf使用

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

    private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");

    private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");

    public static final String DEFAULT_PREFIX = "classpath:/templates/";

    public static final String DEFAULT_SUFFIX = ".html";
    //上面是springmvc中的前缀和后缀

因为默认有前缀和后缀的设置,故只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;

使用:

1、在html页面中导入thymeleaf的名称空间(起提示作用)

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

2、使用thymeleaf语法,举个例子:

<!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>

3、语法规则

1)、简单语法规则

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

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

超链接中网址中带参数,thymeleaf可以用括号表示,如果有多个参数,用逗号隔开:
th:href="@{/index.html(l='zh_CN',user='zg')}"

2)、表达式?

Simple expressions:(表达式语法)
    1.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.

                ${session.foo}
            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).

    2.Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
        补充:配合 th:object="${session.user}:
           <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>

    3.Message Expressions: #{...}:获取国际化内容

    4.Link URL Expressions: @{...}:定义URL;
            @{/order/process(execId=${execId},execType='FAST')}

    5.Fragment Expressions: ~{...}:片段引用表达式
            <div th:insert="~{commons :: main}">...</div>

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)
Special tokens:
    No-Operation: _ 

举例:

<!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 id="div01" class="myDiv" th:id="${hello}" th:class="${hello}" th:text="${hello}">这是显示欢迎信息</div>
<hr/>
<div th:text="${hello}"></div>
<div th:utext="${hello}"></div>
<hr/>
<!-- th:each每次遍历都会生成当前这个标签: 3个h4 -->
<h4 th:text="${user}"  th:each="user:${users}"></h4>
<hr/>
<h4>
    <span th:each="user:${users}"> [[${user}]] </span>
</h4>
</body>
</html>

3)、内联表达式 Expression inlining
使用手册pdf中第12章的内容

在Thymeleaf中,[[…]]或[(…)]之间的表达式被视为内联表达式,在其中,我们可以使用任何能在th:text或th:utext属性中用的表达式。比如说:

<p>Hello, <span th:text="${session.user.name}">Sebastian</span>!</p>
等价于:
<p>Hello, [[${session.user.name}]]!</p>

在一些内联标签只能使用这个内联表达式,如下:

<input type="checkbox" value="remember-me"/> [[#{login.remember}]]

原文地址:https://www.cnblogs.com/baizihua/p/12222641.html

时间: 2024-07-30 23:41:59

模板引擎Thymeleaf的简单了解的相关文章

SpringBoot:模板引擎 Thymeleaf 基础使用

1    第2-3课:模板引擎 Thymeleaf 基础使用 1.1     模板引擎 模板引擎是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的 HTML 文档. 模板引擎的实现方式有很多,最简单的是"置换型"模板引擎,这类模板引擎只是将指定模板内容(字符串)中的特定标记(子字符串)替换,便生成了最终需要的业务数据(如网页). "置换型"模板引擎实现简单,但其效率低下,无法满足高负载的应用需求(比如有海量

Spring MVC : Java模板引擎 Thymeleaf (二)

本文原计划直接介绍Thymeleaf的视图解析,但考虑到学习的方便,决定先构建一个spring-mvc. 下面的所有过程只要一个记事本和JDK就够了. 第一步,使用maven构建一个web app. <span style="font-size:18px;">mvn archetype:generate -DgroupId=org.nwpu.chen -DartifactId=spring-mvc -DarchetypeArtifactId=maven-archetype-

SpringBoot(5)新一代Java模板引擎Thymeleaf

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

Spring Boot基础7-web应用开发-模板引擎Thymeleaf

原文视频参考:http://www.roncoo.com/course/view/c99516ea604d4053908c1768d6deee3d 一.spring boot的web应用开发,是基于spring mvc 二.Spring boot 在spring默认基础上,自动配置添加了以下特性: 1.   包含了ContentNegotiatingViewResolver和BeanNameViewResolver beans. 2.   对静态资源的支持,包括对WebJars的支持. 3.  

Spring MVC : Java模板引擎 Thymeleaf (一)

在Java世界的MVC框架里,使用的视图技术不少,最基本的是JSP,还有知名的FreeMarker和Velocity等模板引擎.Thymeleaf也是一款优秀的模板引擎,它在HTML5/XHTML的视图层表现的很好,也能在离线情况下处理任何XML文件.它是完全可以替代JSP+JSTL的. 下面是来自于Thymeleaf官方的Q&A: Q: 和FreeMarker,Velocity相比,Thymeleaf表现得怎样呢? A:FreeMarker和Velocity都是软件领域杰出的作品,但它们在解决

springboot:Java模板引擎Thymeleaf介绍

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

模板引擎Thymeleaf

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

Spring Boot系列(3)——模板引擎thymeleaf

〇.thymeleaf是什么 1.在以往开发spring web项目时,若我们想在前端页面上显示一些服务端的数据(即动态显示),得借助JSP的内置对象和JSTL实现,或者通过JavaScript请求实现:其缺点在于,与后端联系太紧密,不利于前后端分离. 2.而使用模板引擎,可以大大克服这一缺点,模板引擎可以使得前端很自然地开发(即更接近原生html). 3.模板引擎优点有:业务逻辑代码与界面代码分离.动态数据与静态数据分离.代码重用.... 4.常用模板引擎:Thymeleaf.FreeMark

模板引擎freemarker的简单使用教程

freemarker十分强大,而且不依赖web容器,个人感觉十分好用. 下面直接进主题,freemarker还有什么特性,请找度娘或谷哥~ 一.freemarker生成word 1.创建模板. 我创建模板的方法比较简单,也不知道有没有其他更好的方法,有的话,请告诉我吧~ 首先是新建一个word文档,按照内容格式排好版,然后在需要注入信息的位置先写上占位置的数据,如图1,然后另存为xml文件(我是存为2003版本的xml),然后用文本编辑器把xml打开,在xml中把对应的数据改为freemarke