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

huangapple go评论73阅读模式
英文:

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

值得注意的是,我不仅仅在谈论它在浏览器中的呈现方式;源代码实际上在&lt;/strong&gt;后显示换行;而在&lt;/strong&gt;不存在时没有换行。我已经确认这并不是在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:

&lt;div class=&quot;row mb-1&quot; th:utext=&quot;${item.snippet}&quot;&gt;&lt;/div&gt;

My Java looks like this:

snippet = StringUtils.replaceIgnoreCase(snippet, 
searchText.trim(), 
&quot;&lt;strong&gt;&quot;+searchText.trim().toUpperCase()+&quot;&lt;/strong&gt;&quot;);

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
&lt;strong&gt;JUMPED&lt;/strong&gt;
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 &lt;/strong&gt;; and no newline when the &lt;/strong&gt; 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:"

&lt;div class=&quot;row mb-1&quot;&gt;[(${item.snippet})]&lt;/div&gt;

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:

&lt;div class=&quot;row mb-1&quot;&gt;&lt;th:block th:utext=&quot;${item.snippet}&quot;/&gt;&lt;/div&gt;

The behavior suggests there is additional text processing for some or all tags and &lt;th:block th:utext&quot;...&quot;/&gt; must insulate the target text.

huangapple
  • 本文由 发表于 2020年9月7日 10:40:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63770700.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定