すきま風

勉強したことのメモとか

クソ雑魚バックエンドエンジニアのフロントエンド開発勉強日誌 1

Thymeleaf

HTMLを用意するためにThymeleafを入れます。そこからかよって感じですが、過去にフロントエンド開発をしたときに使っていたフレームワークCatalyst (Perl製のフレームワーク) で、Thymeleaf経験すら皆無なのでやむなし。

Presenter class

テンプレートエンジン内でなんらかの制御やロジックを入れる際、処理は全てPresenter classで行います。テストコードを書いたりデバッグするのに便利で、template file内にビジネスロジックが混入することを防ぐことができます。

presenter

class FrontPracticePresenter(
    private val response: Response
) {
    fun fooLabel() = response.foo.toUpperCase()
}

後は適当に設定をしていきます。

gradle

// versionはdependency managementで管理
implementation("org.springframework.boot:spring-boot-starter-thymeleaf")

controller

@Controller
class FrontPracticeController {
    @GetMapping("front/practice")
    fun sample() = mono {
        Rendering
            .view("front/practice/main")
            .modelAttribute("view", FrontPracticePresenter(Response("foo", "bar"))) // ResponseをPresenterでWrapする
            .build()
    }
}

data class Response(
    val foo: String,
    val bar: String
)

template

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="ja">
<head>
  <title>top page</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div>
  <p>Presenterで出力を加工する</p>
  <p th:text="${view.fooLabel()}" />
</div>
</body>
</html>

中身のない感じですが、とりあえずここまで