1

I want to call javascript function in 'th:if'. This is my code.

<li th:each="dto, stat : ${list}" th:if="${stat.count>10}">
   <span th:if="'javascript:isNew('+${dto.regDts}+');'">blah blah</span>
</li>

...

<script th:inline="javascript">
 function isNew(date) {
     if (...) {
        return true;
     }
     return false;
 }
</script>

but it doesn't call isNew().

so when I wrote like this...

 <span th:if="isNew(${dto.regDts});">blah blah</span>

i got an error.

how can I call javascript function in "th:if"?

  • As far as i know you can not. You should implement a equivalent method in a utility method in a Java Bean and then access it. Take a look at this: https://developpaper.com/springboot-thymeleaf-template-file-calls-java-class-static-methods/ and also this: https://stackoverflow.com/questions/48402821/error-trying-call-method-from-view-thymeleaf-spring – Ahmet Mar 07 '22 at 06:24

1 Answers1

1

Thymeleaf generates HTML in the server and passes that to the browser. At that point, Thymeleaf is no longer "active". JavaScript runs in the browser using the HTML that Thymeleaf has generated. So it is impossible to do what you want like this.

The easiest solution is to add an extra method or property on the Java object that is used. Suppose you add an isNew() method on your dto, then you can do:

<li th:each="dto, stat : ${list}" th:if="${stat.count>10}">
   <span th:if="${dto.new}">blah blah</span>
</li>
Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211