thymeleaf utext / th:utext自己插入换行符,为什么?

问题描述

th:utext中使用简单的html标记似乎导致呈现错误的换行符。为什么会这样,和/或如何预防呢?

我的标记如下:

<div class="row mb-1" th:utext="${item.snippet}"></div>

我的Java看起来像这样:

snippet = StringUtils.replaceIgnoreCase(snippet,searchText.trim(),"<strong>"+searchText.trim().toupperCase()+"</strong>");

snippet为“那只棕色的狐狸跳过了那些懒狗”时; searchText被“跳过”;并且存在strong标签; html呈现如下:

The quick brown fox
<strong>JUMPED</strong>
over the lazy dogs

当我删除strong标记时,html呈现如下:

The quick brown fox JUMPED over the lazy dogs

值得注意的是,我并不是在谈论它在浏览器中的显示方式。源实际上在</strong>之后显示换行符; </strong>不存在时,也没有换行符。我已经确认它也没有添加到Java层中。

解决方法

尝试使用“内联表达式:”

<div class="row mb-1">[(${item.snippet})]</div>

已记录here

关于为什么,我有一个类似的模板,并注意到Thymeleaf 3.0发布后的行为发生了变化。在描述内联表达式时,issue将等效项描述为:

<div class="row mb-1"><th:block th:utext="${item.snippet}"/></div>

此行为表明,对于某些或所有标签还需要进行其他文本处理,并且<th:block th:utext"..."/>必须隔离目标文本。