簡體   English   中英

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

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

在嘗試在 thymeleaf 中使用最大 function 時,我每次都得到 OGNL 表達式。 我什至不確定我們是否可以在 thymeleaf 中使用像 max/min 這樣的函數。試圖在文檔中查找它,但找不到任何足智多謀的東西。 這是我想使用 math.max 的代碼:

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

甚至還嘗試以這種方式使用它: <div th:with="maxNumber=${max(8,12)}">給出了同樣的錯誤。

正如所評論的,雖然 Thymeleaf 中沒有內置 function,但您可以使用特殊的T(...)運算符Math.max(...)調用 staticmax 方法(允許在您的 Javaleaf 中使用數學。)。

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

我認為 thymeleaf 中沒有這樣的 function 但您可以輕松地為相同目的實現條件

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

如果/除非

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

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.

如果您對 Thymeleaf 使用 Spring 依賴項(我不能,所以我不能直接測試它),看起來實用程序邏輯(在這種情況下為最大數量)可以封裝在 Spring Bean 中,以便在 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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM