简体   繁体   English

如何根据 controller 条件隐藏/显示 thymeleaf 字段?

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

I have a Spring MVC application with thymeleaf.我有一个带有 thymeleaf 的 Spring MVC 应用程序。

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...).根据 controller 方法中测试的条件,我想从视图中显示或隐藏 html 元素(输入、跨度、div、按钮......)。

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.例如,在 asp.net 中,如果您想要或不想显示它,您可以执行 myButton.Visible = false (或 true)。

Anything like that available in thymeleaf with spring? thymeleaf 和 spring 中是否有类似的东西? Thanks.谢谢。

You can achieve it by passing the attribute viaorg.springframework.ui.Model and use Thymeleaf's th:if attribute您可以通过org.springframework.ui.Model传递属性并使用 Thymeleaf 的th:if属性来实现它

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资源/模板/膳食站点.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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM