Thymeleaf-如何根据条件将工具提示动态添加到表格单元格

时间:2019-08-25 05:46:24

标签: css thymeleaf

我们正在使用Thymeleaf构建动态表。

某些具有空值的单元格带有“-”号,而具有值的单元格则存储来自对象的某些数据:

<td th:text="${person.getAddress()} ? ${person.getAddress().getCity() : '-'"}

所以当前状态是这样:

<table border=1>
<tr><td>John</td><td>London</td></tr>
<tr><td>Paul</td><td>-</td></tr>
</table>

现在,我们想添加一个工具提示,即当将鼠标悬停在相关的表格单元格上时,可以看到更多数据(例如,该人的完整地址)。

我们找到了this CSS example for tooltip,我们发现最终结果应该是这样的:

<td class="tooltip">London
  <div class="tooltiptext">
     <div>Street: Green</div>
     <div>Number: 123</div>
  </div>
</td>

但是当尝试在Thymeleaf中实现它时,我们陷入了困境。

这是我们尝试的:

<div th:switch="${person.getAddress()}">
  <div th:case="null"><td>-</td></div>
  <div th:case="*">
      <td> // now what? how to both inject value and the sub divs? </td>
  </div>
</div>

我们想到的另一种选择是通过在td th:text=...

内串联完整的HTML来创建

但是这两种方法都非常麻烦。

1 个答案:

答案 0 :(得分:1)

  1. 您可以将safe navigation operatorelvis operator结合使用,而不用使用空检查。
  2. 不需要开关或类似的逻辑。创建几个额外的标签,并将您的逻辑更深入地进入html。
  3. 不要使用.getAddress(),您可以将.address用于具有正确命名的getter / setter的属性。

例如:

<td>
  <span th:text="${person.address?.city} ?: '-'" />
  <div th:unless="${person.address == null}" class="tooltiptext">
     <div>Street: Green</div>
     <div>Number: 123</div>
  </div>
</td>

没有所有花哨的东西,您也可以简单地执行以下操作:

<td th:if="${person.address == null}">-</td>
<td th:if="${person.address != null}">
  <span th:text="${person.address.city}" />
  <div class="tooltiptext">
     <div>Street: Green</div>
     <div>Number: 123</div>
  </div>
</td>