SpringBoot+Thymeleaf模板 实现html文件引入

本文详细介绍了在SpringBoot项目中如何配置并使用Thymeleaf模板引擎,包括application.properties文件的正确配置方法,以及如何在前端页面通过th标签引用其他页面或模块。解决TemplateInputException错误,确保静态页面能够被正确加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考

https://www.jianshu.com/p/acee38389266

https://blog.youkuaiyun.com/h1021456873/article/details/79085505

SpringBoot中使用Thymeleaf模板,需要在项目的application.properties文件中进行相关配置,如下:

spring.thymeleaf.prefix=classpath:webapp/views/   #配置静态页面所在的位置,这里静态文件的位置为resources/webapp/views/

注意啦,前端使用thymeleaf对应的th标签引用其他页面或模块时,需要结合application.properties中配置的路径来对应上指定的文件路径。

下面是application.properties的配置参考:

 

实际应用中,遇到过这个问题,主要原因有可能是指定文件不存在,或者文件路径配置错误(路径要参考配置的路径进行拼接)

参考:https://www.oschina.net/question/1251858_2235767

TemplateInputException: Error resolving template "xx", template might not exist 
or might not be accessible by any of the configured Template Resolvers (template:"views/index" ...)

下面是相关前端页面的代码:

1. structure.html (公共模块文件,用于定义一些公用模块)

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

<!--定义引用模块-->
<div class="layui-header" th:fragment="navBar">
    <!--模块内容-->
</div>

2.index.html (引用定义好的模块Demo,相当于jsp中的include功能)

<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
    <!-- 引用 webapp/views/templates/structure.html 中的navBar模块 -->
    <!-- replace表示替换当前div,使用include则表示引用 -->
    <div th:replace="templates/structure :: navBar">
</body>
</html>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值