当前位置:首页 » 《随便一记》 » 正文

前端模板引擎Thymeleaf的整合和使用

25 人参与  2024年05月07日 11:23  分类 : 《随便一记》  评论

点击全文阅读


目录

一、添加依赖

1.1首先,在项目的构建文件中(比如 Maven 或 Gradle)添加 Thymeleaf 的依赖。例如,对于 Maven 项目,在 pom.xml 文件中添加以下依赖

1.2保存并更新项目依赖

二、配置Thymeleaf

2.1模板位置配置

2.2模板缓存配置

2.3自定义标签配置

三、创建模板文件

3.1创建一个HTML文件

3.2在HTML文件中引入Thymeleaf命名空间

3.3在HTML文件中使用Thymeleaf语法来定义模板内容

3.4在Java代码中加载模板,并将数据传递给模板

3.5将生成的HTML代码响应给客户端

四、控制器中使用Thymeleaf

4.1在Spring Boot中,在pom.xml文件中添加以下依赖项

4.2在Spring MVC控制器类中,使用@Controller注解标记该类,并使用@RequestMapping注解定义处理请求的方法。

4.3创建一个包含Thymeleaf模板的HTML文件,并将其放置在/resources/templates目录下。

4.4运行

五、在模板中使用Thymeleaf语法

5.1输出变量值

5.2判断条件

5.3循环迭代

5.4设置属性

5.5表单处理

总结


一、添加依赖

1.1首先,在项目的构建文件中(比如 Maven 或 Gradle)添加 Thymeleaf 的依赖。例如,对于 Maven 项目,在 pom.xml 文件中添加以下依赖

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

1.2保存并更新项目依赖

这样就完成了Thymeleaf的引入。在你的代码中,你可以使用Thymeleaf提供的标签和表达式来处理模板中的动态内容,并将其渲染为最终的HTML页面。

二、配置Thymeleaf

2.1模板位置配置

可以通过配置 spring.thymeleaf.prefix 和 spring.thymeleaf.suffix 来指定模板文件的位置和后缀

spring.thymeleaf.prefix=/WEB-INF/templates/spring.thymeleaf.suffix=.html

上述配置将会使 Thymeleaf 在 /WEB-INF/templates/ 目录下查找以 .html 结尾的模板文件。

2.2模板缓存配置

Thymeleaf 默认开启了模板缓存,以提高性能。在开发阶段可能需要关闭缓存以方便调试,可以通过配置 spring.thymeleaf.cache 进行设置。

spring.thymeleaf.cache=false

上述配置将会使Thymeleaf的模板缓存

2.3自定义标签配置

Thymeleaf 支持自定义标签,可以在配置中注册自定义标签处理器。

@Configurationpublic class ThymeleafConfig implements ITemplateResolver {        // ...其他配置        @Bean    public SpringResourceTemplateResolver templateResolver() {        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();        // 配置模板位置、缓存等        // ...        return templateResolver;    }        @Bean    public SpringTemplateEngine templateEngine() {        SpringTemplateEngine templateEngine = new SpringTemplateEngine();        templateEngine.setTemplateResolver(templateResolver());        // 注册自定义标签处理器        // ...        return templateEngine;    }    @Bean    public ThymeleafViewResolver viewResolver() {        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();        viewResolver.setTemplateEngine(templateEngine());        // 其他配置        // ...        return viewResolver;    }    // ...其他配置}

上述代码中,通过 templateResolver() 方法配置模板解析器,通过 templateEngine() 方法配置模板引擎,最后通过 viewResolver() 方法配置视图解析器。在 templateResolver()templateEngine() 方法中可以设置一些自定义的属性,如模板位置、缓存等。在 templateEngine() 方法中还可以注册自定义的标签处理器

三、创建模板文件

3.1创建一个HTML文件

将其命名为模板名称,如“template.html"。

3.2在HTML文件中引入Thymeleaf命名空间

<h1 th:text="${title}">Page Title</h1><p th:text="${content}">Page Content</p>

3.3在HTML文件中使用Thymeleaf语法来定义模板内容

<h1 th:text="${title}">Page Title</h1><p th:text="${content}">Page Content</p>

3.4在Java代码中加载模板,并将数据传递给模板

// 加载模板文件Template template = thymeleafTemplateEngine.getTemplate("template.html");// 创建一个上下文对象,用于传递数据给模板Context context = new Context();context.setVariable("title", "My Page Title");context.setVariable("content", "Hello, world!");// 渲染模板并生成HTML代码String renderedHtml = templateEngine.process(template, context);

在上面的例子中,我们使用Thymeleaf模板引擎加载模板文件"template.html",然后创建一个上下文对象并通过它将数据传递给模板。最后,我们调用process()方法来渲染模板,并生成HTML代码。

3.5将生成的HTML代码响应给客户端

response.setContentType("text/html;charset=UTF-8");response.getWriter().write(renderedHtml);

四、控制器中使用Thymeleaf

4.1在Spring Boot中,在pom.xml文件中添加以下依赖项

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

4.2在Spring MVC控制器类中,使用@Controller注解标记该类,并使用@RequestMapping注解定义处理请求的方法。

@Controllerpublic class MyController {    @RequestMapping("/hello")    public String hello(Model model) {        model.addAttribute("message", "Hello, Thymeleaf!");        return "hello";    }}

4.3创建一个包含Thymeleaf模板的HTML文件,并将其放置在/resources/templates目录下。

例如,创建一个名为"hello.html"的文件。在模板中使用Thymeleaf的语法来渲染数据。例如,使用${message}获取在控制器中添加到Model的属性。

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head>    <title>Hello Thymeleaf</title></head><body>    <h1 th:text="${message}"></h1></body></html>

4.4运行

运行应用程序,并访问http://localhost:8080/hello,即可看到渲染后的页面。

五、在模板中使用Thymeleaf语法

5.1输出变量值

使用${}表达式来输出变量的值。

<p th:text="${message}"></p>

5.2判断条件

使用th:ifth:else来实现条件判断。

<p th:if="${user.isAdmin}">管理员</p><p th:unless="${user.isAdmin}">普通用户</p>

5.3循环迭代

使用th:each来遍历集合,使用th:object来指定迭代对象的别名。

<ul>    <li th:each="item : ${items}" th:object="${item}">        <p th:text="${name}"></p>        <p th:text="${price}"></p>    </li></ul>

5.4设置属性

使用th:attr来设置HTML元素的属性,如hrefsrc等。

<a th:href="@{/product/{id}(id=${productId})}" th:attr="title=${productName}">    <img th:src="@{${imageUrl}}" /></a>

5.5表单处理

使用th:fieldth:errors来绑定表单字段和错误信息。

<form th:action="@{/login}" method="post" th:object="${user}">    <label>用户名:<input type="text" th:field="*{username}" /></label>    <span th:errors="*{username}"></span>    <label>密码:<input type="password" th:field="*{password}" /></label>    <span th:errors="*{password}"></span></form>

总结

使用Thymeleaf的步骤包括引入依赖、配置Thymeleaf、创建模板文件、在控制器中使用Thymeleaf和在模板中使用Thymeleaf语法。Thymeleaf提供了强大而灵活的功能,使开发者能够方便地实现数据与页面的动态绑定。


点击全文阅读


本文链接:http://zhangshiyu.com/post/104544.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1