[Java]Thymeleafで各ページ別にOGを設定する

Overview

ThymeleafのLayoutページ利用した構成のWEBサイトで、
TwitterのTweetに各ページ毎のTwitterカードを表示するためのメモ書きです。

Thymeleafのth:fragmentとth:replaceを利用する

最初はいちいちフラグメント付けてたりしたのですが、それはいくらなんでも・・・。
と調べているとどうやらタグ単位で読み込みこめるみたいです。

セレクタとしてタグを指定できるので当然といえば当然なのですが、慣れないとその発想にすぐ思いつかないですね。

除外などの設定は見当たらなかった(ありそうだけど)ので、とりあえずコンテンツ(子ページ)のメタを全部読み込んで親ページに展開するようにしています。

親ページ

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:fragment="layout (meta, body)">
<head>
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:site" content="@TwitterID" />
    <meta th:replace="${meta}" />
</head>
<body>
    <div id="body" th:replace="${body}"></div>
</body>

</html>

コンテンツ(子ページ)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
    th:replace="~{layout/template :: layout(~{::meta}, ~{::body/content()})}">
<head>
    <meta property="og:url" content="ページURL" />
    <meta property="og:title" content="サイトのタイトル" />
    <meta property="og:site_name" content="サイトの名前" />
    <meta property="og:description" content="説明" />
    <meta property="og:type" content="article" />
    <meta property="og:image" content="画像URL" />
</head>
<body>
</body>
</html>

フォローお願いします!

コメント

タイトルとURLをコピーしました