Search code examples
thymeleafconditional-operator

How can I apply style to a div based on condition in thymeleaf?


I have a <div> block which I need to set to display:none or display:block based on the condition. The html looks like this,

<div style="display:none;"> 
    //some html block content
</div>

I've tried the following code in thymeleaf,

<div th:style="${condition} == 'MATCH' ? display:block : display:none"> 
    //some html block content
</div>

But the above expression is not working. throws org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: error message.

I can do th:classappend to set some class and make this work but want to know if elvis/ternary operator will support on thymeleaf th:style tag.


Solution

  • Solved it while posting the question,

    th:style="${condition ? 'display:block' : 'display:none'}" >
    

    would produce the necessary conditional style. If condition is true display is set to block and none if condition is false.

    For admin,

    th:style="${role == 'ADMIN' ? 'display:block' : 'display:none'}" >
    

    the style is set to display:block and for other roles the block is not displayed.