Home > OS >  Thymeleaf - How to handle the null value and assign different value based on the condition?
Thymeleaf - How to handle the null value and assign different value based on the condition?

Time:03-14

In my case, the condition is if the question.objQuestion.questionContent is null, show the question.sbjQuestion.questionContent. My attempt is shown at below. But it doesn't work.

<td th:switch = "${question.objQuestion.questionContent}"> 
    <span th:case="${question.objQuestion.questionContent == null}" th:text = "${question.objQuestion.questionContent}"></span>
    <span th:case="${question.objQuestion.questionContent != null}" th:text ="${question.sbjQuestion.questionContent}"></span>
</td>

enter image description here obj_question_id and sbj_question_id are foregin id

CodePudding user response:

If you're using a th:switch, the th:case attributes should only contain the value to test. In your case, it should look like this:

<td th:switch="${question.objQuestion.questionContent}"> 
    <span th:case="null" th:text="${question.sbjQuestion.questionContent}"></span>
    <span th:case="*" th:text ="${question.objQuestion.questionContent}"></span>
</td>

You could probably simplify this and just use the Elvis operator:

<td> 
    <span th:text="${question.objQuestion.questionContent} ?: ${question.sbjQuestion.questionContent}"></span>
</td>

CodePudding user response:

It works when I use the Elvis Operator ? in this way

The solution is attached at below:

<td>
   <span th:text = "${question.objQuestion?.questionContent}"></span>
   <span th:text = "${question.sbjQuestion?.questionContent}"></span>
</td>
  • Related