春だから Spring やろうぜ(その 2)
テンプレートを使ってみる
出力する文字列に HTML を直接打てば表示はされるけど当然ながら面倒くさい。
そこで Thymeleaf というテンプレートを使うことにする。
先ほどの app.groovy と同じフォルダに新たに templates というフォルダを作り、その中に index.html を置く。
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Top page</title> </head> <body> <h1 th:text="${title}"/> <p th:text="${msg}"/> </body> </html>
普通の HTML の中に名前空間を使って Thymeleaf 用の属性を埋め込んでる感じ。
app.groovy を修正する。
@Grab("thymeleaf-spring5") @Controller class MyBootApp { @RequestMapping("/") @ResponseBody def top(ModelAndView mv) { mv.setViewName("index") mv.addObject("title", "Hello!") mv.addObject("msg", "Welcome to Thymeleaf!") } }
ほほー。コントローラーから渡した値もちゃんと埋め込まれてる。(続く)