Reputation: 375
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.
Upvotes: 2
Views: 4220
Reputation: 20487
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(java.lang.Math).max(8,12)}">
<p th:text=${maxNumber}></p>
</div>
Upvotes: 2
Reputation: 4509
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();
}
Upvotes: 0
Reputation: 4171
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.
Upvotes: 0