'How to use math.max in thymeleaf to find maximum number?

While trying to use max function in thymeleaf I got OGNL expressionn everytime. I'm not even sure if we can use functions like max/min in thymeleaf. Tried to look for it on the documentation, but couldn't find anything resourceful. This is the code where I want to use math.max :

  <div th:with="maxNumber=${#max(8,12)}">
     <p th:text=${maxNumber}></p>
  </div>

even tried to use it in this way also : <div th:with="maxNumber=${max(8,12)}"> that gave the same error.



Solution 1:[1]

As commented, while there is no built in function in Thymeleaf, you can use the special T(...) operator to call static methods (allowing you to use Java's Math.max(...) in your Thymeleaf).

<div th:with="maxNumber=${T(Math).max(8,12)}">
  <p th:text=${maxNumber}></p>
</div>

Solution 2:[2]

I don't think there is such a function in thymeleaf but you could easily implement conditionals for the same purpose

 <p th:text="8 > 12 ? 8 : 12"></p>

same can be achieved with if/unless

<p th:if = "${foo} > ${bar}" th:text = ${foo}></p>
<p th:if = "${foo} > ${bar}" th:text = ${bar}></p>

there is even switch in thymeleaf baeldung.com/spring-thymeleaf-conditionals

If really neded you can create a class with all the necessary funcitonality in Java and pass that class as a variable to Thymeleaf in model.

Solution 3:[3]

If you are using the Spring dependency for Thymeleaf (which I couldn't, so I couldn't directly test this), looks like the utility logic (max number in this case) could be encapsulated in a Spring Bean to be referenced in Thymeleaf:

https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html#spring-beans

<div th:text="${@urlService.getApplicationUrl()}">...</div>
@Configuration
public class MyConfiguration {
  @Bean(name = "urlService")
  public UrlService urlService() {
    return () -> "domain.com/myapp";
  }
}

public interface UrlService {
  String getApplicationUrl();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Metroids
Solution 2 J Asgarov
Solution 3 cellepo