LoginSignup
60
42

More than 5 years have passed since last update.

Hugoで画像や動画を投稿する時はShortcodeを使おう

Posted at

概要

Hugoでブログを投稿する上で画像やYouTubeの動画を埋め込む際、いつも同じHTMLタグの塊をmarkdownファイルに書いていませんか?
Shortcodeを使うとそんな処理が共通化できてすっきりします。

Partial TemplateではなくShortcode

Theme内でHTMLを細かく切り出して再利用できるようにしているPartial Templateがありますが、こちらはmarkdownファイルの中では使えません。代わりにShortcodeを使います。

サンプル

定義済みのShortcode

Hugo内には以下のfigure様なShortcodeがいくつか定義されています。{{< shortcode名 引数 >}}}で使えます。

markdownファイル内の記述
{{< figure src="/media/spf13.jpg" title="Steve Francia" >}}
出力されるhtmlファイル
<figure>
    <img src="/media/spf13.jpg"  />
    <figcaption>
        <h4>Steve Francia</h4>
    </figcaption>
</figure>

Shortcodeの自作

/layouts/shortcodes/shortcode名.htmlでファイルを置くことでmarkdownの中から利用できます。shortcodeファイル内ではGoコードで様々なHugoやその他のリソースにアクセスが可能です。

例えば、YouTubeの動画埋め込み記述を共通化したい場合は以下のようyoutubeのshortcodeを用意します。

markdownファイル内の記述
{{< youtube 09jf3ow9jfw >}}
/layouts/shortcodes/youtube.html
<div class="embed video-player">
  <iframe class="youtube-player" type="text/html" width="640" height="385" src="http://www.youtube.com/embed/{{ index .Params 0 }}" allowfullscreen frameborder="0"></iframe>
</div>
出力されるhtmlファイル
<div class="embed video-player">
<iframe class="youtube-player" type="text/html"
    width="640" height="385"
    src="http://www.youtube.com/embed/09jf3ow9jfw"
    allowfullscreen frameborder="0">
</iframe>
</div>

タイトル付きで画像を埋め込みたい場合は以下の様なimgタグを用意すると良いでしょう。

markdownファイル内の記述
{{< img src="/media/spf13.jpg" title="Steve Francia" >}}
/layouts/shortcodes/img.html
<!-- image -->
<figure {{ with .Get "class" }}class="{{.}}"{{ end }}>
    {{ with .Get "link"}}<a href="{{.}}">{{ end }}
        <img src="{{ .Get "src" }}" {{ if or (.Get "alt") (.Get "caption") }}alt="{{ with .Get "alt"}}{{.}}{{else}}{{ .Get "caption" }}{{ end }}"{{ end }} />
    {{ if .Get "link"}}</a>{{ end }}
    {{ if or (or (.Get "title") (.Get "caption")) (.Get "attr")}}
    <figcaption>{{ if isset .Params "title" }}
        <h4>{{ .Get "title" }}</h4>{{ end }}
        {{ if or (.Get "caption") (.Get "attr")}}<p>
        {{ .Get "caption" }}
        {{ with .Get "attrlink"}}<a href="{{.}}"> {{ end }}
            {{ .Get "attr" }}
        {{ if .Get "attrlink"}}</a> {{ end }}
        </p> {{ end }}
    </figcaption>
    {{ end }}
</figure>
<!-- image -->

参考

公式ドキュメントを見ると、ここに掲載したもの以外のサンプルも掲載されているので参考になります。

60
42
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
60
42