[java] Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

By using Thymeleaf as template engine, is it possible to add/remove dynamically a CSS class to/from a simple div with the th:if clause?

Normally, I could use the conditional clause as follows:

<a href="lorem-ipsum.html" th:if="${condition}">Lorem Ipsum</a> 

We will be creating a link to the lorem ipsum page, but only if condition clause is true.

I'm looking for something different: I'd like the block to always visible, but with changeable classes according to the situation.

This question is related to java html css spring thymeleaf

The answer is


Another very similar answer is to use "equals" instead of "contains".

<li th:class="${#strings.equals(pageTitle,'How It Works')} ? active : ''">

For this purpose and if i dont have boolean variable i use the following:

<li th:class="${#strings.contains(content.language,'CZ')} ? active : ''">

What @Nilsi mentioned is perfectly correct. However, adminclass and user class need to be wrapped in single quotes as this might fail due to Thymeleaf looking for adminClass or userclass variables which should be strings. That said,

it should be: -

 <a href="" class="baseclass" th:classappend="${isAdmin} ? 'adminclass' : 
 'userclass'"> 
 </a>

or just:

<a href="" th:class="${isAdmin} ? 'newclass' : 
  'baseclass'"> 
 </a>

Just to add my own opinion, in case it might be useful to someone. This is what I used.

<div th:class="${request.read ? 'mdl-color-text--grey-800 w500' : ''}"> </div>

Yet another usage of th:class, same as @NewbLeech and @Charles have posted, but simplified to maximum if there is no "else" case:

<input th:class="${#fields.hasErrors('password')} ? formFieldHasError" />

Does not include class attribute if #fields.hasErrors('password') is false.


If you are looking to add or remove class accordingly if the url contains certain params or not .This is what you can do

<a th:href="@{/admin/home}"  th:class="${#httpServletRequest.requestURI.contains('home')} ? 'nav-link active' : 'nav-link'"  >

If the url contains 'home' then active class will be added and vice versa.


Just in case someone is using Bootstrap, I was able to add more than one class:

<a href="" class="baseclass" th:classappend="${isAdmin} ?: 'text-danger font-italic' "></a>

Yes, it is possible to change a CSS class dynamically according to the situation, but not with th:if. This is done with the elvis operator.

<a href="lorem-ipsum.html" th:class="${isAdmin}? adminclass : userclass">Lorem Ipsum</a> 

If you just want to append a class in case of an error you can use th:errorclass="my-error-class" mentionned in the doc.

<input type="text" th:field="*{datePlanted}" class="small" th:errorclass="fieldError" />

Applied to a form field tag (input, select, textarea…), it will read the name of the field to be examined from any existing name or th:field attributes in the same tag, and then append the specified CSS class to the tag if such field has any associated errors


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to thymeleaf

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers Setting up a JavaScript variable from Spring model by using Thymeleaf Thymeleaf: how to use conditionals to dynamically add/remove a CSS class How to set thymeleaf th:field value from other variable Using Thymeleaf when the value is null How to avoid the "Circular view path" exception with Spring MVC test Thymeleaf: Concatenation - Could not parse as expression How to do if-else in Thymeleaf?