Thymeleaf学习教程

Thymeleaf学习教程

一、Thymeleaf简介

Thymeleaf是一个Java模板引擎,它能够处理HTML、XML、JavaScript、CSS甚至纯文本。Thymeleaf的主要特点是它能够在浏览器中直接显示模板(具有自然模板模式),并且可以在服务器端和客户端进行渲染,这使得它在Web开发中非常流行,特别是在基于Java的Web框架(如Spring Boot)中。

二、环境搭建

1. 创建Maven项目(以Maven为例)

  • 使用你喜欢的IDE(如IntelliJ IDEA或Eclipse)创建一个新的Maven项目。
  • pom.xml文件中添加以下依赖:
<project>
    <!-- 其他项目配置 -->
    <dependencies>
        <!-- Thymeleaf核心依赖 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.14.RELEASE</version>
        </dependency>
        <!-- 与Spring集成的依赖(如果用于Spring项目) -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.14.RELEASE</version>
        </dependency>
    </dependencies>
</project>

2. 创建基本项目结构

  • src/main/resources目录下创建templates文件夹,这是Thymeleaf默认的模板存放位置。

三、基础语法

1. 命名空间声明

  • 在HTML文件的<html>标签中添加Thymeleaf的命名空间声明:
<html lang="en" xmlns:th="http://www.thymeleaf.org">

2. 文本替换(th:text

  • 这是最基本的Thymeleaf属性,用于替换HTML标签中的文本内容。
  • 示例:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf Example</title>
</head>
<body>
    <p th:text="'Hello, Thymeleaf!'">This is a default text</p>
</body>
</html>
  • 在这个例子中,<p>标签中的默认文本This is a default text将会被Hello, Thymeleaf!替换。

3. 表达式求值

  • 变量表达式(${...}
    • 用于获取服务器端传递过来的变量值。
    • 首先,在Java代码(如Spring控制器)中设置一个变量并将其添加到模型中:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MainController {
   
   

    @RequestMapping("/")
    public String index(Model model)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值