本文介绍了Thymeleaf:用< br>替换换行符。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个可能包含换行符的字段(< textarea name =desc/>
),我想用它们的HTML副词替换它们:< br />
。我怎样才能做到这一点?我正在使用Thymeleaf 2.1.4.RELEASE。
I have a field (<textarea name="desc" />
) that may contain newlines and I want to replace them with their HTML counterpart: <br />
. How can I do this? I'm using Thymeleaf 2.1.4.RELEASE.
推荐答案
As in JSP, it's not possible to use simple and straightforward
${#strings.replace(desc, '\n', '<br />')}
'\n' is treated by underlying expression language (SpEL in my case as I'm using Spring MVC) as string literal that consist of two separate characters: '\' and 'n' rather than single newline character
exception is being thrown as the Thymeleaf underlying XML parser does not allow to put
<
and>
inside expressions
我找到的第一个问题的解决方案是在控制器中设置换行符并将其传递给查看。
要解决第二个问题你需要使用
& lt;
而不是<
和& gt;
而不是>
。还记得这意味着使用 th:utext
而不是 th:text
// in controller:
model.addAttribute("newLineChar", '\n');
// in view
${#strings.replace(desc, newLineChar, '<br />')}
${#strings.replace(desc, T(System).getProperty('line.separator'), '<br />')}
我最终将要使用的是上面+ Apache StringUtils定义
public static final String LF =\ n;
:
${#strings.replace(desc, T(org.apache.commons.lang3.StringUtils).LF, '<br />')}
这篇关于Thymeleaf:用< br>替换换行符。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!