Home > database >  Thymeleaf inline javascript spring bean check for null with textual template modes
Thymeleaf inline javascript spring bean check for null with textual template modes

Time:11-25

I can't wrap my head around the syntax of the Textual template modes feature of Thymeleaf. Im trying to access a bean (works fine) and call a getter from where i get an another object from. This object can be null and i need to check it before i access the string i need.

How can i do this in one line by using the [# th:if expressions from Thymeleaf?

<script th:inline="javascript">
        //This does not work (i have tried multiple things)
        var string = /*[# th:if="${@bean.getObject()}"][[${@bean.getObject().getString()}]][/]*/ null;
</script>

CodePudding user response:

There are a lot of ways to accomplish this, I would recommend the safe navigation operator for this:

<script th:inline="javascript">
  var string = /*[[${@bean.object?.string}]]*/ null;
</script>

You could also use a ternary expression:

<script th:inline="javascript">
  var string = /*[[${@bean.object != null ? @bean.object.string : null}]]*/ null;
</script>
  • Related