【问题标题】:Concatenate strings from an object in th:each with Thymeleaf将 th:each 中对象的字符串与 Thymeleaf 连接起来
【发布时间】:2020-03-09 14:05:44
【问题描述】:

我有一个服务台(带有 javaEe、Spring 和 thymeleaf),他给我发了一本具有这种形状的对象书:

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

我需要从 BooksAuthors 对象列表中提取作者姓名,如下所示:

public class BooksAuthors   {
  @JsonProperty("firstName")
  private String firstName;

  @JsonProperty("lastName")
  private String lastName;
...

我想在表格中显示有关作者的信息,但我不知道如何使用 Thymeleaf。我认为这将是一个 th:each 来解析作者,在一个 th:each 内部来解析书籍,但我无法让它工作。 我想要的结果是

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

我设法得到了结果。我试图创建一个 var 并将其连接起来,但我仍然必须删除最后一个“,”。更重要的是,它在我看来非常笨拙。

<td>
    <span th:each="author:${book.getAuthors()}"
          th:with="authorName=${author.getFirstName()} + ' ' + ${author.getLastName()} + ', '"
          th:text="${authorName}">
    </span>
</td>

我想知道是否有更好更简单的解决方案?或者我应该在我的业务层而不是在百里香中做吗? 非常感谢!

【问题讨论】:

    标签: java spring thymeleaf


    【解决方案1】:

    我猜你可以为此使用迭代状态对象:

    https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#keeping-iteration-status

    制作这样的东西:

    <span th:each="author, iterStat:${book.getAuthors()}"
                  th:with="authorName=${author.getFirstName()} + ' ' + ${author.getLastName() + ${iterStat.count != iterStat.size ? ',' : ''}}"
                  th:text="${authorName}">
    </span> 
    

    【讨论】:

    • 非常感谢!它需要稍作修改才能工作&lt;td&gt; &lt;span th:each="author:${book.getAuthors()}" th:with="authorName=${author.getFirstName()} + ' ' + ${author.getLastName()} + ${authorStat.count != iterStat.size ? ', ' : ''}" th:text="${authorName}"&gt;&lt;/span&gt; &lt;/td&gt;。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 2020-12-08
    • 2014-08-30
    • 2019-08-24
    相关资源
    最近更新 更多