0

I have an ArrayList in my mvc controller class:

List<Market> markets = loadMarkets();

I add this list to Model object:

model.addAttribute("markets", markets);

In my template, when I want to get size() of this array:

<span>Top <strong th:text="${markets.size}"></strong>assets.</span>

I got this error:

Cannot evaluate because of compilation error(s): The method size() is undefined for the type Object.

Snapshot of the VSCode debugging tools:

enter image description here

I am using Spring Boot version 2.2.6.RELEASE with Thymeleaf template engine.

Ali Behzadian Nejad
  • 8,804
  • 8
  • 56
  • 106
  • 1
    According to your error message you have a Java code compilation error: ``model.getAttribute("markets").size()` - not a Thymeleaf expression evaluation error. You can't find the `size()` of an `Object` (which is what you get returned from the `getAttribute()` method). Comment out (or delete) that line of Java code and try again. See if you get a different error - or no error at all. – andrewJames Jun 10 '21 at 23:55
  • 1
    Does this answer your question? [How to print Array size in thymeleaf?](https://stackoverflow.com/questions/43484142/how-to-print-array-size-in-thymeleaf) note says array size, but is about array lists. There is utility methods in thymeleaf for this – Darren Forsythe Jun 11 '21 at 00:07
  • 1
    Just to clarify: The Thymeleaf expression in the question works as written: `th:text="${markets.size}"`. Yes, there are Thymeleaf utility objects - such as this: `th:text="${#lists.size(markets)}"` - but I don't think this is needed here. It's the Java code which needs to be fixed (or removed, if not needed). – andrewJames Jun 11 '21 at 00:56
  • 1
    Isn't the problem that you are using `size` property which tries to call `getSize()`, but there is no such method? I think you need to explictly call the `size()` method like this: `th:text="${markets.size()}"` – Wim Deblauwe Jun 11 '21 at 06:17
  • Using `${markets.size()}` solved the problem. – Ali Behzadian Nejad Jun 11 '21 at 08:11

1 Answers1

0

When you use property notation th:text="${markets.size}", then Thymeleaf will search for a method getSize() on the markets attribute in the model. But there is no getSize() method, only size() method.

So use the method itself instead of using the property notation:

th:text="${markets.size()}"
Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211
  • This caught me by surprise. I have `List people = ...`, where `Person` is a JavaBean. When I use `th:text="${people.size}"`, I get the expected result - and no errors. This is in plain Thymeleaf (no Spring), in case that is a factor. – andrewJames Jun 11 '21 at 12:44
  • Ah, I always use Thymeleaf with Spring, so maybe there is a difference there indeed. – Wim Deblauwe Jun 14 '21 at 06:08