I have a service rest (with javaEe, Spring and thymeleaf) who sends me an object book with this shape:
public class BookDto {
@JsonProperty("id")
private Long id;
@JsonProperty("isbn")
private String isbn;
@JsonProperty("title")
private String title;
@JsonProperty("authors")
@Valid
private List<BooksAuthors> authors;
...
I need to extract the authors name from the list of BooksAuthors object which looks like that:
public class BooksAuthors {
@JsonProperty("firstName")
private String firstName;
@JsonProperty("lastName")
private String lastName;
...
I would like to display in a table the informations about the authors, but i don't know how to do it with Thymeleaf. I think it will be a th:each to parse the authors, inside a th:each to parse the books, but i can't make it work. The result i would like would be
<table class="table">
<thead>
<tr>
<th scope="col">Titre</th>
<th scope="col">Auteur</th>
<th scope="col">isbn</th>
<th scope="col">Exemplaires disponibles</th>
</tr>
</thead>
<tbody>
<tr th:each="book:${books}">
<td th:text="${book.getTitle()}"></td>
<td>Author1, Author2</td>
<td th:text="${book.getIsbn()}"></td>
<td>Pas implémenté</td>
</tr>
</tbody>
</table>
I manage to have a result. I tried to create a var and concatenate it but i still have to remove the last ','. And more important, it looks very clumsy to me.
<td>
<span th:each="author:${book.getAuthors()}"
th:with="authorName=${author.getFirstName()} + ' ' + ${author.getLastName()} + ', '"
th:text="${authorName}">
</span>
</td>
I'm wondering if there is a nicer and simpler solution for that? Or should i do it in my business layer and not in thymeleaf? Thanks a lot !
I guess you can use iteration status object for this:
https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#keeping-iteration-status
to make something like this:
<span th:each="author, iterStat:${book.getAuthors()}"
th:with="authorName=${author.getFirstName()} + ' ' + ${author.getLastName() + ${iterStat.count != iterStat.size ? ',' : ''}}"
th:text="${authorName}">
</span>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.