0

I need Thymeleaf to always include a label element but only conditionally show a value for it.

If message.type is equal to warning it should show the message.text. Otherwise, the HTML DOM should still contain the label element.

I've tried this but then the label element is missing from the HTML when the message.type is not equal to warning.

<label id="message" th:if="${message.type == 'warning'}" th:value="${message.text}" th:text="${message.text}"></label> 

I'm trying to accomplish something like this:

<label id="message" th:value="${message.type=='warning' ? message.text: ''}" th:text="${message.type=='warning'? message.text: ''"></label> 

If the message.type is warning, I would expect HTML like this:

<label id="message">My warning message</label> 

Otherwise, I would like to have HTML like this:

<label id="message"></label> 

1 Answer 1

1

Many different ways to accomplish this. You already have one that I would expect to work. (why do you say it doesn't work?) Also, I'm not sure why you are including th:value in your tags (I'm including them to match your question).

<label id="message" th:value="${message.type == 'warning'? message.text : ''}" th:text="${message.type == 'warning'? message.text : ''}"></label> 

You could also do something like this:

<label th:if="${message.type == 'warning'}" id="message" th:value="${message.text}" th:text="${message.text}"></label> <label th:unless="${message.type == 'warning'}" id="message"></label> 

or like this (assuming an extra span wouldn't mess up the markup you are wanting):

<label id="message"><span th:if="${message.type == 'warning'}" th:text="${message.text}" /></label> 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. The ternary op works. Looks like I had a typo in my code. Also, it was not working for an enum that I was using. I was treating it the same as a string but found that I needed to handle as in this answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.