在th:each循环中输出Spring百里香限制文本

时间:2019-03-14 09:04:23

标签: java spring thymeleaf

我目前正在做一个学校项目,几乎完成了。我有一个管理面板,其中列出了我的博客文章,我想限制文本字段,以便当其达到150个字符时,它会中断并键入3个点“ ...”。

列表的代码在这里:

 <tr th:each = "blog: ${blogs}">
        <th th:text="${blog.title}" scope="row"></th>
        <td><p th:text="${blog.text}"></p></td>
        <td><p th:text="${blog.author}"></p></td>
        <td><p th:text="${blog.date}"></p></td>
        <td><a th:href="@{/blog/delete/{id}(id=${blog.id})}"class="btn btn-danger">Delete</a><a th:href="@{/blog/update/{id}(id=${blog.id})}" class="btn btn-info ml-2">Edit</a></td>
    </tr>

我尝试在Google上进行搜索,但找不到解决方案。

感谢您的帮助!

/尼克

1 个答案:

答案 0 :(得分:1)

如果您不想使用CSS进行操作,则可以按照以下步骤进行操作:

<td><p th:text="${#strings.length(blog.text)>150 ? #strings.substring(blog.text,0,150) + '...'} : blog.text"></p></td>

编辑: 搜索更多后,发现此简单方法:

<td><p th:text="${#strings.abbreviate(blog.text,150)} "></p></td>

这是执行先前解决方案的简写形式。您可以在here中找到详细信息。