在 Thymeleaf 中渲染多行字符串 [英] Rendering a multiline string in Thymeleaf

查看:73
本文介绍了在 Thymeleaf 中渲染多行字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题的一个变体中,我想使用 Thymeleaf 将多行字符串渲染到 HTML 表格中.>

也就是说,我如何转换像

这样的字符串

Cronut fixie 凌乱的 migas.无论中性内脏腰包,照相亭媚俗定制吊床赃物.Keffiyeh yuccie 冥想小胡子玉米洞古.

进入

<tr><td>Cronut fixie 凌乱的 migas.</td></tr><tr><td>任何中性的内脏腰包,照相亭媚俗定制吊床赃物.</td></tr><tr><td>Keffiyeh yuccie 冥想小胡子玉米洞古.</td></tr>

解决方案

使用包含在模型变量 model.text 中的字符串,一个可能的解决方案(当使用 Spring 方言时)是这样的:

<tr th:each="line : ${#strings.arraySplit(model.text, T(org.apache.commons.lang3.StringUtils).LF)}"><td th:text="${line}"></td></tr>

使用 T(org.apache.commons.lang3.StringUtils).LF 而不是 \n 的原因是(也如 这个答案) SpEL 转义反斜杠,然后决定在 'n' 字母而不是换行符上拆分.

当然,也应该考虑直接在控制器中将字符串拆分为数组的解决方案(即使用纯Java).

In a variant of this question, I want to render a multiline string into an HTML table using Thymeleaf.

That is, how do I convert a string like

Cronut fixie tousled migas.
Whatever neutra offal fanny pack, photo booth kitsch bespoke hammock swag.
Keffiyeh yuccie meditation mustache cornhole paleo.

into

<table class="table">
    <tr>
        <td>Cronut fixie tousled migas.</td>
    </tr>
    <tr>
        <td>Whatever neutra offal fanny pack, photo booth kitsch bespoke hammock swag.</td>
    </tr>
    <tr>
        <td>Keffiyeh yuccie meditation mustache cornhole paleo.</td>
    </tr>
</table>

解决方案

With the string contained in the model variable model.text, a possible solution (when using the Spring dialect) is this:

<table>
    <tr th:each="line : ${#strings.arraySplit(model.text, T(org.apache.commons.lang3.StringUtils).LF)}">
        <td th:text="${line}"></td>
    </tr>
</table>

The reason for using T(org.apache.commons.lang3.StringUtils).LF instead of just \n is that (as also described in this answer) SpEL escapes the backslash, and then decides to split on 'n'-letters instead of newlines.

Of course, one should also consider the solution of just splitting the string into an array directly in the controller (i.e. using plain Java).

这篇关于在 Thymeleaf 中渲染多行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆