【Hugo】Render Hooks for Code Blocksを利用してコードブロックにファイル名を表示する
更新日:2022.09.04
作成日:2022.09.03
Hugo v0.93.0
からコードブロックに対してもRender Hooks
を利用できるようになった。
Render Hooks
を利用して、コードブロックにファイル名を表示する方法を調べたときのメモを以下に残しておく。
Release v0.93.0 · gohugoio/hugo
Render Hooks for Code Blocksを利用してコードブロックにファイル名を表示する
Render Hooks for Code Blocks
を利用することで下図のとおり、コードブロックの上部にファイル名を表示できる。

Markdown
{name="content/blog/blogcard.md"}
の形式でAttributes
(name
)を指定すると、Render Hooks
側でファイル名(.Attributes.name
)を取得できる。
```html {name="content/blog/blogcard.md"}
{{< blogcard "https://www.meganii.com/blog/2022/08/14/migration-from-github-to-cloudflare-pages/" >}}
{{< blogcard "https://www.meganii.com/blog/2022/08/11/proxying-cloudinary-with-cloudflare-workers/" >}}
{{< blogcard "http://example.com" >}}
```
Render Hooks for Code Block
下記のとおり、layouts/_default/_markup/render-codeblock.html
を作成する。
layouts/_default/_markup/render-codeblock.html
<div>
{{- $name := .Attributes.name -}}
{{ with $name }}<div class="codeblock--name">{{ . }}</div>{{ end }}
<div class="codeblock--content">
{{- highlight (.Inner | safeHTML) .Type .Options }}
</div>
</div>
2022年9月3日現在このブログでは、TailwindCSS
を使っているので、以下のようなCSSを当てている。
<div>
{{- $name := .Attributes.name -}}
{{ with $name }}<div class="codeblock--name w-fit text-sm text-white bg-gray-600 mt-1 py-1 px-1.5 rounded-t-lg">{{ . }}</div>{{ end }}
<div class="codeblock--content">
{{- highlight (.Inner | safeHTML) .Type .Options }}
</div>
</div>
参考
Related contents

TECH
2022.08.29
Hugoでブログカードを作成する(resources.GetRemote利用)

TECH
2022.08.14
GitHub PagesからCloudflare Pagesへの移行

TECH
2022.06.29
AMP Service WorkerでPrefetch Linksを実現する

TECH
2023.02.03
Hugo v0.109.0でパンくずリストをシンプルに実装する

TECH
2021.02.11
Git pre-commitフックでFrontmatterの「更新日時」を自動更新する

TECH
2021.01.24
「Hugoで始める静的サイト構築入門 静的サイトジェネレーターで作る自作サイト」を出版しました

TECH
2021.01.09
GitHub Actionsのスケジューラ実行を利用して定期的にビルドする

TECH
2020.12.26
Hugoでブログ記事一覧ページ(ブログアーカイブページ)を作成する