【问题标题】:How to hide/show thymeleaf fields based on controller condition?如何根据控制器条件隐藏/显示百里香字段?
【发布时间】:2020-12-14 16:17:44
【问题描述】:

我有一个带有 thymeleaf 的 Spring MVC 应用程序。

根据控制器方法中测试的条件,我想在视图中显示或隐藏 html 元素(输入、跨度、div、按钮...)。

如何做到这一点?例如,在 asp.net 中,如果您想要或不想显示它,您可以执行 myButton.Visible = false(或 true)。

百里香和春天有类似的东西吗?谢谢。

【问题讨论】:

    标签: java spring spring-mvc thymeleaf


    【解决方案1】:

    你可以通过传递属性来实现它 org.springframework.ui.Model 并使用 Thymeleaf 的 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;
    
    @Controller
    public class MealController {
    
        @GetMapping("/order")
        public String getCondition(@RequestParam(required = false) String myMeal, Model model) {
            model.addAttribute("meal", myMeal);
            return "meal/meal-site";
        }
    }
    

    资源/模板/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>
    

    【讨论】:

    • 太棒了。工作完美。也适用于 ModelAndView。谢谢你。已接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    相关资源
    最近更新 更多