タイトル: Thymeleaf
SEOタイトル: Thymeleaf 入門: Spring Boot 標準テンプレートの記法・レイアウト・JSP との違い
| この記事の要点 |
|
Thymeleaf とは
Thymeleaf は Spring Boot 標準のテンプレートエンジン。最大の特徴は th: 属性で記述するため素の HTML としてブラウザで開けること。デザイナーがそのまま編集できるため、JSP に比べて開発フローが分業しやすい。
| 項目 | Thymeleaf | JSP |
|---|---|---|
| HTML として開ける | ◯ | × |
| Spring Boot 標準 | ◯ | △ (要設定) |
| 記法 | HTML 属性 th:* | カスタムタグ |
| レイアウト | fragment / decorator | include / sitemesh |
| 学習コスト | 低(HTML が分かれば) | 中 |
セットアップ (Spring Boot)
org.springframework.boot
spring-boot-starter-thymeleaf
src/main/resources/
├── templates/ ← Thymeleaf テンプレート (デフォルト)
│ ├── index.html
│ └── user/
│ ├── list.html
│ └── detail.html
└── static/ ← CSS / JS / 画像
├── css/app.css
└── js/app.js
基本記法
タイトル
山田太郎
紹介文
詳細
管理者です
一般ユーザーです
管理者
ユーザー
ゲスト
- 名前
1
名前
フォーム
Spring MVC との連携
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public String list(Model model) {
model.addAttribute("users", userService.findAll());
model.addAttribute("title", "ユーザー一覧");
return "user/list"; // → templates/user/list.html
}
@GetMapping("/new")
public String form(Model model) {
model.addAttribute("form", new UserForm());
return "user/edit";
}
@PostMapping("/save")
public String save(@Valid @ModelAttribute("form") UserForm form,
BindingResult result,
RedirectAttributes ra) {
if (result.hasErrors()) return "user/edit";
userService.save(form);
ra.addFlashAttribute("message", "保存しました");
return "redirect:/user";
}
}
レイアウト (fragment)
共通ヘッダ・フッタを切り出して再利用:
共通
サンプルサイト
ユーザー一覧
ユーザー一覧
th:replace と th:insert の違い:
| 属性 | 動作 |
|---|---|
th:replace | 呼び出し側のタグごと置換 |
th:insert | 呼び出し側のタグ中に挿入 |
th:include | fragment の中身のみ挿入(非推奨、3.0+ で deprecated) |
JS / CSS との連携
ユーティリティオブジェクト
2000/01/01
1,234.56
YAMADA
短縮...
10
000-0000
FAQ
Q: th:text と th:utext の違い
A: th:text は HTML エスケープあり(XSS 安全)、th:utext はエスケープなし(XSS 注意、自己責任)。原則 th:text。
Q: Thymeleaf 2 と 3 の違い
A: 3.0 から th:include 廃止、~{...} fragment 構文導入、HTML5 への移行など。Spring Boot 2.0+ は Thymeleaf 3 が標準。
Q: 開発中に変更が反映されない
A: spring.thymeleaf.cache=false を application.properties に。または DevTools を入れる。本番は cache=true。