How to hide/show thymeleaf fields based on controller condition?

Tags: , , ,

I have a Spring MVC application with thymeleaf.

Depending on a condition tested in the controller method I want to show or hide an html element from the view (input, span, div, button…).

How to do that? For instance, in you can do myButton.Visible = false (or true) if you want or don’t want to display it.

Anything like that available in thymeleaf with spring? Thanks.


You can achieve it by passing the attribute via org.springframework.ui.Model and use Thymeleaf’s th:if attribute


package com.example.demo.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

public class MealController {

    public String getCondition(@RequestParam(required = false) String myMeal, Model model) {
        model.addAttribute("meal", myMeal);
        return "meal/meal-site";


<!DOCTYPE html>
<html lang="en" xmlns:th="">
    <meta charset="UTF-8">
    <title>Hot Dog?</title>
    <div th:if="'hotdog' == ${meal}">A hotdog! 🌭</div>
    <div th:if="'hotdog' != ${meal}">Not a hotdog 😢</div>

Source: stackoverflow