ひとくちThymeleaf Tips disabledプロパティの適用
「Thymeleafってこんな機能があるんだ」という気分になってくれたらいいなという、Thymeleafの機能について一口サイズで紹介させていただく記事です。
非活性のステータスにするth:disabled
htmlの標準機能にある「disabled」を条件付きで指定できるthタグです。
通常のhtmlだと「disabled」の付与自体は可能なのですが、動的に「disabled」する/しないを切り替えるためにはjavaScriptなど外部からの制御が必要。
基本的に「活性/非活性」はセットで動的に切り替えられるように作るはずなので、そんな時に便利なthタグです。
記法
以下の{条件式}がtrueの場合のみ、「disabled」が適用されます。
th:disabled="{条件式}"
使用例
htmlに紐づけてあるFormオブジェクト「doClick(boolean型)」のステータスを見て、disabledを切り替える例です。
htmlヘッダなど細かい部分は割愛します。
「doClick」がfalseの場合のみボタンにdiabledが適用されます。「クリックし手非活性に」ボタンを押下すると「doClick」にfalseが設定されるように記載。
Hello.html
<body>
<h1>Hello World</h1>
<form method="post" action="/hello/post" th:object="${helloForm}">
<span th:text="*{demoText}"></span>
<input type="submit" value="クリックして非活性に" th:disabled="*{doClick == false}">
</form>
</body>
DemoController.java
@Controller
@RequestMapping("/hello")
public class DemoController {
@GetMapping
public String getHello(Model model,@ModelAttribute HelloForm form) {
String url="demo/hello.html";
form.setDemoText("ステータス切り替え前");
form.setDoClick(true);
return url;
}
@PostMapping("post")
public String getPost(Model model,@ModelAttribute HelloForm form) {
String url="demo/hello.html";
form.setDemoText("ステータス切り替え後");
form.setDoClick(false);
return url;
}
}
HelloForm.java
@Data
public class HelloForm {
private String demoText;
private boolean doClick;
}