问题描述
我有一个可能包含换行符的字段(< 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'由底层表达式语言(在我的情况下是SpEL,因为我使用的是Spring MVC)处理为字符串文字,由两个单独的字符组成:'\'和'n'而不是单个换行符 $ b由于Thymeleaf底层XML解析器不允许放置
<
和>
异常>内部表达式 - '\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
我找到的第一个问题的解决方案是在控制器中设置换行符并将其传递给查看。
The solution I found for the first problem is to set newline character in a controller and pass it to view.
要解决第二个问题你需要使用& lt;
而不是<
和& gt;
而不是>
。还记得这意味着使用 th:utext
而不是 th:text
To address the second problem you need to use <
instead of <
and >
instead of >
. Also remember that this implies using th:utext
instead of th:text
// in controller:
model.addAttribute("newLineChar", '\n');
// in view
${#strings.replace(desc, newLineChar, '<br />')}
如果您使用Thymeleaf + Spring(这意味着Thymeleaf将使用SpEL而不是OGNL),您也可以使用SpEL T运算符
。这样您就不必在控制器中声明换行符了,但请注意,在这种情况下换行符分隔符会因应用程序运行的操作系统而异:
If you are using Thymeleaf + Spring (what means that Thymeleaf will use SpEL instead of OGNL), you may also use SpEL T operator
.This way you don't have to declare the newline variable in your controller but mind out that newline separator in this case will vary across operating systems that your app is running on:
${#strings.replace(desc, T(System).getProperty('line.separator'), '<br />')}
我最终将要使用的是上面+ Apache StringUtils定义 public static final String LF =\ n;
:
What I'm going to finally use is the combination of the above + Apache StringUtils that defines public static final String LF = "\n";
:
${#strings.replace(desc, T(org.apache.commons.lang3.StringUtils).LF, '<br />')}
这篇关于Thymeleaf:用< br>替换换行符。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!