0

I have a generic thymeleaf table as follows:

 <tbody>
        <th:block th:each="row : ${page.getContent()}">
            <tr>
                 <td th:each="header : ${headers}" th:text="${row.__${header}__}"/>
            </tr>
        </th:block>
    </tbody>

The table is simply backed by a list containing my domain objects:

List<Header> headers = List.of("firstname", "lastname");
List<Person> page;

What it does is: it loops my predefined list headers, and selects only those attributes defined in the headers list.

Question: how could I add an evaluation on the classtype of the extracted value of each field, so that I could apply a custom style in case of digits?

The problem is: when I output the class of the value that is shown, the output is a java.util.ArrayList always!

th:text="${{row.__${header}__}.class.name}"

Why doesn't this show the correct class of the td element?

membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • `X.getClass() instanceof Y` is never useful. `X.getClass()` always returns an instance of `Class` and nothing else. It's either `X instanceof Y` or `x.getClass().equals(Y)` – Michael Jun 11 '19 at 16:15
  • have you tried `head.class.name instanceof T(java.math.BigDecimal)`? – riddle_me_this Jun 11 '19 at 22:57
  • Possible duplicate of [Use instanceof in Thymeleaf](https://stackoverflow.com/questions/28783272/use-instanceof-in-thymeleaf) – riddle_me_this Jun 11 '19 at 22:57
  • @bphilipnyc see my update. I tried all the suggestions, but still cannot access the class type. – membersound Jun 12 '19 at 09:04

2 Answers2

1

You should be able to evaluate the header if you go down a level. My thought is that the preprocessor operation may not give you a reference to the header object on the same td element.

This use case may also be a good candidate for th:classappend since you may want to inherit some style.

Also, not sure whether it applies, but table headings are typically wrapped in a <thead> element. Then, I would assume you'd want a list of Person objects iterated in a <tbody>.

Haven't tested it, but try:

<thead>
     <th:block th:each="header : ${headers}">
          <th th:text="${header}" class="someClass" th:classappend="${header.name.class instanceof T(java.math.BigDecimal) ? 'someDigitClassStyle' : ''}" />
      </th:block> 
<thead>

Assumes use of Spring. Reference

Lastly, you can consider an Apache util for isNumeric if you want to more broadly catch digits.

riddle_me_this
  • 8,575
  • 10
  • 55
  • 80
0

Solution as follows to apply a specific css style based on instance check:

 th:text="${row.__${header}__}"
 th:style="${{row.__${header}__}.get(0) instanceof T(java.math.BigDecimal)} ? 'text-align:right' : ''"/>
membersound
  • 81,582
  • 193
  • 585
  • 1,120