tbsmcd.net
Dark mode
index, archives, tags, search, profile

OGP イメージに resource を使う

なぜいまさら

hugo で画像を最適化(リサイズ)して出力したのときに画像を /static/images/ から /content/post/[各記事]/ 以下に移動させたわけだが、完全に OGP タグのことを忘れていた。

変更点

/layouts/partials/head_custom.html

< <meta property="og:image" content="{{if .Params.image}}https://tbsmcd.net{{.Params.image}}{{else}}https://tbsmcd.net/images/icon_mono.jpg{{end}}" />
---
> {{ if .Params.image }}
> {{ $src := .Params.image }}
> {{ $resource := .Page.Resources.GetMatch $src }}
> <meta property="og:image" content="https://tbsmcd.net{{ $resource.Permalink }}" />
> {{ else }}
> <meta property="og:image" content="https://tbsmcd.net/images/icon_mono.jpg" />
> {{ end }}

記事ディレクトリ直下にある画像のうち OGP に使いたいファイル名を index.md のメタデータ部分に image: "hoge.jpg" と書いておけば展開される。image: "hoge.jpg" がない場合はデフォルトの画像が表示される。記事直下にない画像ファイルを指定した場合はビルドでエラーになるので気付くことができる。

Tags: hugo