简体   繁体   English

如何使用 thymeleaf 中的 math.max 找到最大数?

[英]How to use math.max in thymeleaf to find maximum number?

While trying to use max function in thymeleaf I got OGNL expressionn everytime.在尝试在 thymeleaf 中使用最大 function 时,我每次都得到 OGNL 表达式。 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.我什至不确定我们是否可以在 thymeleaf 中使用像 max/min 这样的函数。试图在文档中查找它,但找不到任何足智多谋的东西。 This is the code where I want to use math.max:这是我想使用 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.甚至还尝试以这种方式使用它: <div th:with="maxNumber=${max(8,12)}">给出了同样的错误。

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).正如所评论的,虽然 Thymeleaf 中没有内置 function,但您可以使用特殊的T(...)运算符Math.max(...)调用 staticmax 方法(允许在您的 Javaleaf 中使用数学。)。

<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我认为 thymeleaf 中没有这样的 function 但您可以轻松地为相同目的实现条件

 <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 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 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:如果您对 Thymeleaf 使用 Spring 依赖项(我不能,所以我不能直接测试它),看起来实用程序逻辑(在这种情况下为最大数量)可以封装在 Spring Bean 中,以便在 Thymeleaf 中引用:

https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html#spring-beans 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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