Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 893
Lucky Avatar asked Aug 26 '16 11:08

Lucky


2 Answers

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.

like image 150
Lucky Avatar answered Oct 09 '22 12:10

Lucky


In simple case it could be written as

<div th:style="${filed==null} ? 'opacity:.3'">
like image 37
Grigory Kislin Avatar answered Oct 09 '22 12:10

Grigory Kislin