Search code examples
javaspringspring-mvcthymeleaf

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


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 asp.net 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.


Solution

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

    Demo:

    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;
    
    @Controller
    public class MealController {
    
        @GetMapping("/order")
        public String getCondition(@RequestParam(required = false) String myMeal, Model model) {
            model.addAttribute("meal", myMeal);
            return "meal/meal-site";
        }
    }
    

    resources/templates/meal-site.html

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