简体   繁体   中英

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.

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>

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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM