You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Thymeleaf模板布局时如何为th:replace替换片段添加换行

Thymeleaf模板渲染换行问题解决方案

这个问题本质是Thymeleaf默认开启了空白字符移除,且默认关闭了HTML格式化输出,导致多个连续link标签被合并为一行输出,可通过以下方式解决:

方案1:开启全局格式化输出(推荐)

Spring Boot项目

直接在application.properties配置文件中添加以下配置:

# 开启Thymeleaf美化输出,自动对标签进行换行、缩进处理
spring.thymeleaf.pretty-print=true
# 关闭自动移除尾部空白字符
spring.thymeleaf.remove-trailing-whitespace=false

如果是application.yml格式,配置如下:

spring:
  thymeleaf:
    pretty-print: true
    remove-trailing-whitespace: false

配置完成后重启项目即可,渲染后的HTML会自动按照规范换行缩进。

普通Java Web项目

在Thymeleaf模板引擎的初始化代码中开启格式化配置:

@Bean
public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
    // 开启美化输出
    templateEngine.setPrettyPrint(true);
    return templateEngine;
}

方案2:局部调整(无需修改全局配置)

如果不想改动全局配置,可以在主页面的每个link标签末尾添加一个空注释,强制Thymeleaf保留换行:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="template/layout/base :: common_header(~{::title},~{::link})">
<title>Main title</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"><!-- -->
<link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}"><!-- -->
</head>
<body>
main content
</body>
</html>

空注释会打断Thymeleaf的空白合并逻辑,让每个link标签单独占一行输出。

内容的提问来源于stack exchange,提问作者emarwa.mouma.35t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:15:03