Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring thymeleaf limit text output in a th:each loop

I am currently making a school project and is almost done. I have an admin panel where I have listed my blogposts, and I want to limit the text field so when it reaches 150 characters it will break and type 3 dots "..."..

The code for the list is here:

 <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>

I have tried to search on google, but can't find a solution.

Thanks for your help!

/Nick

like image 558
Nick Kisbye Hansen Avatar asked Jan 27 '23 14:01

Nick Kisbye Hansen


1 Answers

If you dont want to do it by CSS you can do it as follows:

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

EDIT: After searching more found this easy method:

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

Which is a short hand notation for doing the previous solution. You can find details in here.

like image 110
Ahmet Avatar answered Feb 02 '23 12:02

Ahmet