msano / Hugoに画像を追加したい

Created Sun, 11 Jan 2026 19:53:34 +0000 Modified Sun, 11 Jan 2026 21:21:11 +0000
534 Words

hugoでの画像の挿入方法について書きます。

mdファイル画像を挿入する際に <image src='path/to/the/image' width='300' alt='this is an image'>のように書きたかったのですが画像が画面に反映されず、

調べてShortcodesにたどりつきました。

Shortcodes: 

A shortcode is a template invoked within markup, accepting any number of arguments. They can be used with any content format to insert elements such as videos, images, and social media embeds into your content.

早速手順をご紹介します。

まず既存のHugoのディレクトリのうちcontentlayoutsを次のように変更します。

post1 の配下に記事と画像を置き、layoutsの配下に_shortcodes/img.htmlを置きます。

.
├── content
│      └── post1
│         ├── index.md
│         └── post1-image.png  
└── layouts
       └── _shortcodes 
          └── img.html

次に _shortcodes/img.htmlの内容を書きましょう。

{{ $image := .Page.Resources.Get (.Get "src") }}
{{ $alt := .Get "alt" }}
{{ $width := .Get "width" }}
{{ with $image }}
  <img src="{{ .RelPermalink }}" {{if $alt}}alt="{{ $alt }}"{{ end }} {{ if $width }}width="{{ $width }}"{{ end }}>
{{ else }}
  <p>image not found</p>
{{ end }}

最後に content/post1/index.mdに次のラインを追加します。

 {< img src="post1-image.png" width="400" alt="post1-image">}

※ 都合上、波括弧を使っていますが実際は2重波括弧で書いてください。

あとはビルドし画面を再読み込みをすれば反映されます!

この書き方だと、シンプルにサイズを指定できるのでとても気に入っています。

参考