如何在使用Thymeleaf时在页面上显示适当的消息,如果列表为空。

huangapple go评论63阅读模式
英文:

How to show appropriate message on page with Thymeleaf if list is empty

问题

以下是翻译好的部分:

我有一些控制器与一些列表相连,现在这个列表可能是空的,我正在尝试在页面上为用户提供一个消息,如果列表为空。为了更明确,用户可以拥有钱包,在钱包内创建交易,因为所有这些,我有一个名为`Transactions`的页面,如果用户还没有创建任何交易但访问了该页面,我想显示一条消息,类似于`您还没有创建任何交易`。

我找到了这个示例,并尝试应用到我的问题上,但到目前为止没有成功:https://stackoverflow.com/questions/51301074/how-to-check-null-and-empty-condition-using-thymeleaf-in-one-single-operation

这是我的控制器:

@GetMapping("/userTransactions/{user_id}")
public String getUserTransactions(@PathVariable("user_id") long user_id, TransactionGroup transactionGroup, Model model) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
    long userId = user.getId();
    model.addAttribute("userId", userId);

    List<Transaction> transactions = transactionRepository.getTransactionsByUserId(user_id);
    List<TransactionGroup> transactionByDate = new ArrayList<>();
    List<Transaction> transOnSingleDate = new ArrayList<>();
    boolean currDates = transactions.stream().findFirst().isPresent();

    if (currDates) {
        LocalDate currDate = transactions.get(0).getDate();

        TransactionGroup transGroup = new TransactionGroup();

        for (Transaction t : transactions) {
            if (!currDate.isEqual(t.getDate())) {
                transGroup.setDate(currDate);
                transGroup.setTransactions(transOnSingleDate);
                transactionByDate.add(transGroup);
                transGroup = new TransactionGroup();
                transOnSingleDate = new ArrayList<>();
            }

            transOnSingleDate add(t);
            currDate = t.getDate();
        }
        transGroup.setDate(currDate);
        transGroup.setTransactions(transOnSingleDate);

        transactionByDate.add(transGroup);
    } else {
        System.out.println("Empty");
        model.addAttribute("transactionGroup", "NoData");
    }
    model.addAttribute("transactionGroup", transactionByDate);
    return "transactions";
}

这似乎工作得很好,我是说,如果我没有创建交易,将打印消息`System.out.println("Empty");`,但页面上的消息也不显示。

这是Thymeleaf的部分:

<div class="date" th:each="singleGroup  : ${transactionGroup}">
    <h1 th:text="${singleGroup.date}"></h1>
    <div class="transaction" th:each="singleTrans  : ${singleGroup.transactions}">
        <h2>Amount: <span th:text="${singleTrans.amount}"></span></h2><br>
        <h2>Note: <span th:text="${singleTrans.note}"></span></h2><br>
        <h2>Wallet name: <span th:text="${singleTrans.walletName}"></span></h2><br>
        <h2>Expense Category: <span th:text="${singleTrans.expenseCategories}"></span></h2><br>
        <h2>Income Category: <span th:text="${singleTrans.incomeCategories}"></span></h2>
        <a class="card__link" th:href="@{/api/transaction/delete/{id}(id=${singleTrans.id})}"
           th:data-confirm-delete="|Are you sure you want to delete ${singleTrans.walletName} wallet?|"
           onclick="if (!confirm(this.getAttribute('data-confirm-delete'))) return false">Delete</a>
        <hr>
    </div>
    <th:block th:if="${transactionGroup=='NoData'}"> No Data Found </th:block>
</div>

希望这对你有所帮助。如果你有任何其他问题,可以继续提出。

英文:

I have some controller that is connected with some lists, now that list can be empty, I'm trying to provide a user message on page if list is empty. To be more clear, user can have wallet, inside that wallet user can create a transactions, because all of that I have a page Transactions now, if user still didnt create any transaction but visit that page, I want to show him message like You didnt create any transaction.

I found this example, and tried to apply on my problem, but so far it didnt work: https://stackoverflow.com/questions/51301074/how-to-check-null-and-empty-condition-using-thymeleaf-in-one-single-operation

This is my controller:

@GetMapping(&quot;/userTransactions/{user_id}&quot;)
public String getUserTransactions(@PathVariable(&quot;user_id&quot;) long user_id, TransactionGroup transactionGroup, Model model) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
    long userId = user.getId();
    model.addAttribute(&quot;userId&quot;, userId);

    List&lt;Transaction&gt; transactions = transactionRepository.getTransactionsByUserId(user_id);
    List&lt;TransactionGroup&gt; transactionByDate = new ArrayList&lt;&gt;();
    List&lt;Transaction&gt; transOnSingleDate = new ArrayList&lt;&gt;();
    boolean currDates = transactions.stream().findFirst().isPresent();

    if (currDates) {
        LocalDate currDate = transactions.get(0).getDate();

        TransactionGroup transGroup = new TransactionGroup();

        for (Transaction t : transactions) {
            if (!currDate.isEqual(t.getDate())) {
                transGroup.setDate(currDate);
                transGroup.setTransactions(transOnSingleDate);
                transactionByDate.add(transGroup);
                transGroup = new TransactionGroup();
                transOnSingleDate = new ArrayList&lt;&gt;();
            }

            transOnSingleDate.add(t);
            currDate = t.getDate();
        }
        transGroup.setDate(currDate);
        transGroup.setTransactions(transOnSingleDate);

        transactionByDate.add(transGroup);
    } else {
        System.out.println(&quot;Empty&quot;);
        model.addAttribute(&quot;transactionGroup&quot;, &quot;NoData&quot;);
    }
    model.addAttribute(&quot;transactionGroup&quot;, transactionByDate);
    return &quot;transactions&quot;;
}

And that seems to work fine, I mean, if I didn't create a transaction, message System.out.println(&quot;Empty&quot;); will be printed, but message on page is not displayed neither.

This is thymeleaf:

    &lt;div class=&quot;date&quot; th:each=&quot;singleGroup  : ${transactionGroup}&quot;&gt;
    &lt;h1 th:text=&quot;${singleGroup .date}&quot;&gt;&lt;/h1&gt;
    &lt;div class=&quot;transaction&quot; th:each=&quot;singleTrans  : ${singleGroup.transactions}&quot;&gt;
        &lt;h2&gt;Amount: &lt;span th:text=&quot;${singleTrans.amount}&quot;&gt;&lt;/span&gt;&lt;/h2&gt;&lt;br&gt;
        &lt;h2&gt;Note: &lt;span th:text=&quot;${singleTrans.note}&quot;&gt;&lt;/span&gt;&lt;/h2&gt;&lt;br&gt;
        &lt;h2&gt;Wallet name: &lt;span th:text=&quot;${singleTrans .walletName}&quot;&gt;&lt;/span&gt;&lt;/h2&gt;&lt;br&gt;
        &lt;h2&gt;Expense Category: &lt;span th:text=&quot;${singleTrans .expenseCategories}&quot;&gt;&lt;/span&gt;&lt;/h2&gt;&lt;br&gt;
        &lt;h2&gt;IncomeCategory: &lt;span th:text=&quot;${singleTrans .incomeCategories}&quot;&gt;&lt;/span&gt;&lt;/h2&gt;
        &lt;a class=&quot;card__link&quot; th:href=&quot;@{/api/transaction/delete/{id}(id=${singleTrans.id})}&quot;
           th:data-confirm-delete=&quot;|Are you sure you want to delete ${singleTrans.walletName} wallet?|&quot;
           onclick=&quot;if (!confirm(this.getAttribute(&#39;data-confirm-delete&#39;))) return false&quot;&gt;Delete&lt;/a&gt;
        &lt;hr&gt;
    &lt;/div&gt;
    &lt;th:block th:if=&quot;${transactionGroup==&#39;NoData&#39;}&quot;&gt; No Data Found &lt;/th:block&gt;
&lt;/div&gt;

And here is the part: &lt;th:block th:if=&quot;${transactionGroup==&#39;NoData&#39;}&quot;&gt; No Data Found &lt;/th:block&gt; But its not displayed if list is empty

What I'm missing?

答案1

得分: 1

你可以像这样检查你的列表是否为空

<div th:if="${#lists.isEmpty(transactionGroup)}"> 没有找到数据 </div>
<div th:if="${#lists.size(transactionGroup) == 0}"> 没有找到数据 </div>

另外,你的th:block应该放在列表的外部循环之外,这就是当列表为空时你看不到任何东西的原因。

英文:

You can check if your list is empty like this

&lt;div th:if=&quot;${#lists.isEmpty(transactionGroup)}&quot;&gt; No Data Found &lt;/div&gt;

&lt;div th:if=&quot;${#lists.size(transactionGroup) ==0}&quot;&gt; No Data Found &lt;/div&gt;

In addition to that, your th:block is placed inside the list outer loop and it should be outside. That's why you're not seeing anything when the list is empty.

huangapple
  • 本文由 发表于 2023年2月19日 03:55:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496021.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定