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

Thymeleaf utext不遵循HTML结构问题修复咨询

问题根源

HTML规范禁止<a>标签嵌套<a>标签,你的代码中将包含内部<a>的description区块包裹在外层跳转<a>中,浏览器为修复这个无效HTML结构,自动拆分了外层<a>标签,导致渲染结果异常——这和Thymeleaf的utext属性无关,utext已经正确输出了HTML内容。

修复方案

方案1:拆分跳转区域(推荐)

只将卡片头部设置为跳转链接,彻底避免<a>嵌套问题:

<div id="subject-card" th:each="subject: ${subjects}">
   <a th:href="'./subject/' + ${subject.id}">
      <div id="card-header">
         <p id="title" th:text="${subject.name}"></p>
         <div id="subject-info">
            <p id="subject-state" th:text="${subject.state}"></p>
            <p id="is-subject-confidential" th:if="${subject.confidential}" th:text="Confidential"></p>
         </div>
      </div>
   </a>

   <div id="description">
      <th:block th:utext="${subject.description}"></th:block>
   </div>

   <p id="owner" th:if="${subject.owner != null}" th:text="${'Owner: ' + subject.owner.firstname+ ' ' + subject.owner.lastname}"></p>
</div>

方案2:JavaScript实现全卡片跳转(保留内部链接)

如果需要整个卡片(除内部链接外)点击跳转,用JS实现并阻止内部链接的事件冒泡:

Thymeleaf代码

<div id="subject-card" th:each="subject: ${subjects}" th:data-subject-id="${subject.id}" onclick="handleCardClick(this)">
   <div id="card-header">
      <p id="title" th:text="${subject.name}"></p>
      <div id="subject-info">
         <p id="subject-state" th:text="${subject.state}"></p>
         <p id="is-subject-confidential" th:if="${subject.confidential}" th:text="Confidential"></p>
      </div>
   </div>

   <div id="description">
      <th:block th:utext="${subject.description}"></th:block>
   </div>

   <p id="owner" th:if="${subject.owner != null}" th:text="${'Owner: ' + subject.owner.firstname+ ' ' + subject.owner.lastname}"></p>
</div>

对应JS代码

function handleCardClick(element) {
   const subjectId = element.dataset.subjectId;
   window.location.href = `./subject/${subjectId}`;
}

// 阻止内部链接触发卡片跳转
document.addEventListener('click', e => {
   if (e.target.tagName === 'A' && e.target.closest('#subject-card')) {
      e.stopPropagation();
   }
});

内容的提问来源于stack exchange,提问作者Zerak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:25:23