How to do a if else in thymeleaf inside a loop that populate a table

大城市里の小女人 提交于 2021-01-29 04:07:40

问题


I'm populating a table using a <tr th:each> and I want to put a if statement that evaluates the value if it is null, if the values is null I want to put this "--" instead of "null".

How can I do this using the th:if or other similar function I am new using thymeleaf?

This is my code:

<table id="datatable_fixed_column" class="table table-striped table-bordered" width="100%">
  <thead>
    <tr>
        <th>name</th>
        <th>lastname</th>
     <tr>
   <tbody>
      <tr th:each="nodeInfo : ${listOfData}">
        <td  th:if="${nodeInfo.name} == 'null'"> -- </td>
        <td  th:if="${nodeInfo.name} != 'null'" th:text="${nodeInfo.name}"></td>

EDITED: the code was edited and its working


回答1:


Just change your code to:

<tr th:each="nodeInfo : ${listOfData}">
   <td  th:if="${nodeInfo.name} == null">This is the value if the name is null</td>
   <td  th:if="${nodeInfo.name} != null">This is the value if the name is NOT null</td>
</tr>

Or even more consisely you could write:

<tr th:each="nodeInfo : ${listOfData}">
   <td  th:if="!${nodeInfo.name}">This is the value if the name is null</td>
   <td  th:if="${nodeInfo.name}">This is the value if the name is NOT null</td>
</tr>

which works because ${nodeInfo.name} is evaluated to true when name is not null

You could also explore the use of th:unless instead of using !=

Check out this part of the documentation for more details.



来源:https://stackoverflow.com/questions/26062218/how-to-do-a-if-else-in-thymeleaf-inside-a-loop-that-populate-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!