英文:
thymeleaf utext / th:utext is inserting a newline on its own, why?
问题
使用简单的HTML标签在th:utext
中似乎会导致错误的换行呈现出来。为什么会这样,和/或者我该如何阻止它?
我的标记看起来像这样:
<div class="row mb-1" th:utext="${item.snippet}"></div>
我的Java代码看起来像这样:
snippet = StringUtils.replaceIgnoreCase(snippet,
searchText.trim(),
"<strong>"+searchText.trim().toUpperCase()+"</strong>");
当snippet
为"The quick brown fox jumped over the lazy dogs";searchText
为"jumped";并且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层面添加的换行。
英文:
The use of simple html tags in a th:utext
appears to be causing an errant newline to be rendered. Why is that, and/or how do I prevent it?
My markup looks like this:
<div class="row mb-1" th:utext="${item.snippet}"></div>
My Java looks like this:
snippet = StringUtils.replaceIgnoreCase(snippet,
searchText.trim(),
"<strong>"+searchText.trim().toUpperCase()+"</strong>");
When snippet
is "The quick brown fox jumped over the lazy dogs"; searchText
is "jumped"; and the strong
tags are present; the html is rendered like this:
The quick brown fox
<strong>JUMPED</strong>
over the lazy dogs
When I remove the strong
tags, the html is rendered like this:
The quick brown fox JUMPED over the lazy dogs
Of note, I'm not talking JUST about how it appears in the browser; the source actually shows a newline after the </strong>
; and no newline when the </strong>
isn't present. I have confirmed it's not being added in the Java layer, as well.
答案1
得分: 1
尝试使用“内联表达式”:
<div class="row mb-1">[(${item.snippet})]</div>
在此处文档有说明。
至于为什么,我有一个类似的模板,并注意到在发布Thymeleaf 3.0版本后行为发生了变化。在描述内联表达式时,问题将其等价描述为:
<div class="row mb-1"><th:block th:utext="${item.snippet}"/></div>
这种行为表明对一些或所有标签进行了额外的文本处理,而<th:block th:utext="${item.snippet}"/>
必须隔离目标文本。
英文:
Try using an "inline expression:"
<div class="row mb-1">[(${item.snippet})]</div>
documented here.
As for why, I had a similar template and noticed the behavior change upon the release of Thymeleaf 3.0. When describing inline expressions, the issue describes the equivalent as:
<div class="row mb-1"><th:block th:utext="${item.snippet}"/></div>
The behavior suggests there is additional text processing for some or all tags and <th:block th:utext"..."/>
must insulate the target text.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论