はじめに
Hugoで記事を書いているときに、とても長い文章やインストールログを貼り付けることがある。
そのときに、HTMLタグにあるdetailsタグを使いたいのだが、detailsタグ内ではマークダウンが使えないため、意図しないレイアウトで表示されてしまう。
今回は、上記を改善できるように独自のShortCodeとしてdetailsタグを実装してみようと思う。
環境
MacOS Sonoma 14.5
Docker Desktop 4.30.0 (149282)
hugo v0.122.0+extended linux/amd64 BuildDate=unknown現状
detailsタグをHTMLとしてそのまま書いた場合どうなるかを実践する。
detailsタグを書く
例えば以下のようなインストールログを貼り付けたとする。
<details>
<summary>ログ</summary>
~/workspace/blog-hugo$make new file=post/tech/environment/use-details-tag-shortcode-on-hugo.md [master|✔ ]
make up
docker compose up -d
[+] Running 2/2
✔ Container blog-hugo-hugo-1 Started 0.4s
✔ Container blog-hugo-tcardgen-1 Started 0.4s
docker compose exec hugo hugo new post/tech/environment/use-details-tag-shortcode-on-hugo.md
Content "/src/content/post/tech/environment/use-details-tag-shortcode-on-hugo.md" created
</details>ログ
```sh ~/workspace/blog-hugo$make new file=post/tech/environment/use-details-tag-shortcode-on-hugo.md [master|✔ ] make up docker compose up -d [+] Running 2/2 ✔ Container blog-hugo-hugo-1 Started 0.4s ✔ Container blog-hugo-tcardgen-1 Started 0.4s docker compose exec hugo hugo new post/tech/environment/use-details-tag-shortcode-on-hugo.md Content "/src/content/post/tech/environment/use-details-tag-shortcode-on-hugo.md" created ```※ summaryタグの後にコードブロックの構文を入れている。
この場合だと、レイアウトが崩れているのがわかる。
改善
Shotcodeを作る
layouts/shortcodes/details.html を作成する。
<details>
<summary>{{ (.Get 0) | markdownify }}</summary>
{{ .Inner | markdownify }}
</details>これでOK
使い方
※例では{}にスペースを入れてタグとして認識されないようにしている。
{ {< details ログ>} }
~/workspace/blog-hugo$make new file=post/tech/environment/use-details-tag-shortcode-on-hugo.md [master|✔ ]
make up
docker compose up -d
[+] Running 2/2
✔ Container blog-hugo-hugo-1 Started 0.4s
✔ Container blog-hugo-tcardgen-1 Started 0.4s
docker compose exec hugo hugo new post/tech/environment/use-details-tag-shortcode-on-hugo.md
Content "/src/content/post/tech/environment/use-details-tag-shortcode-on-hugo.md" created
{ {< /details >} }実例は下記になる。
ログ
~/workspace/blog-hugo$make new file=post/tech/environment/use-details-tag-shortcode-on-hugo.md [master|✔ ]
make up
docker compose up -d
[+] Running 2/2
✔ Container blog-hugo-hugo-1 Started 0.4s
✔ Container blog-hugo-tcardgen-1 Started 0.4s
docker compose exec hugo hugo new post/tech/environment/use-details-tag-shortcode-on-hugo.md
Content "/src/content/post/tech/environment/use-details-tag-shortcode-on-hugo.md" createdHugoでは、HTMLをレンダリングする際に、SafeHTMLでエスケープ処理されているため、このようになっている。
https://gohugo.io/functions/safe/html/
そのため、Shortcodeを作成することでそれを回避して実現している。
参考
Add collapsible section in hugo
https://stackoverflow.com/questions/71691219/add-collapsible-section-in-hugoCharGPT 会話ログ
https://chatgpt.com/share/9e09cc0c-cd46-4e26-98d9-5b8b80131661
おわりに
今まで、detailsタグを使うとレイアウトが崩れていたので使用していなかったのだが、Shortcode経由で使えるようになってかなり嬉しい。
これでもう少し見やすい記事が作れるようになったのではないかと思う。
閲覧者側からすると、インストールした際のログとかは記事の本質部分ではないと思うので。