Hugo で markdown ファイル内に <!--ad-->
と入力すると Google Adsense の広告ユニットのコードに置換されるようにしてみました。
ショートコード使わなくてもできた。
参考
実装
adsense広告ユニットのコードが入った partial template を作る
layouts/partials/adsense-inarticle.html
{{ if .Site.IsServer }}
{{ else }}
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3245444835923925"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-3245444835923925"
data-ad-slot="7737093919"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
{{ end }}
data-ad-client と data-ad-slot の値は config.toml(yaml, json) に書く方が美しいかもしれませんが、ひとまずそのままコピペしてきました。
{{ if .Site.IsServer }} ~ {{ else }} ~ {{ end }}
で、サーバー実行中には出力されないようにしています。
config.toml の編集
[markup]
[markup.goldmark]
[markup.goldmark.renderer]
unsafe = true
Hugo 既定の Markdown parser になっている goldmark の設定をします。
unsafe By default, Goldmark does not render raw HTMLs and potentially dangerous links. If you have lots of inline HTML and/or JavaScript, you may need to turn this on. Configure Markup | Hugo
inline JavaScript を有効にしないといけないので、unsafe = true
にします。
シングルテンプレートを編集
layouts/_default/single.html
{{- if .Content }}
<div class="post-content">
{{- if not (.Param "disableAnchoredHeadings") }}
{{ $content := replace .Content "<!--ad-->" (partial "adsense-inarticle.html" .) | safeHTML }}
{{- partial "anchored_headings.html" $content -}}
{{- else }}{{ replace .Content "<!--ad-->" (partial "adsense-inarticle.html" .) | safeHTML }}{{ end }}
</div>
{{- end }}
<!--ad-->
を広告コードに置換するように {{ .Content }} に対して replace を使います。
Hugo-PaperMod の single.html では2ヶ所ある。
anchored_headings.html と結合している方は、次のコードで
{{ $content := replace .Content "<!--ad-->" (partial "adsense-inarticle.html" .) | safeHTML }}
置換した {{ .Content }} を $content に入れてから後の処理をしてもらうことにした(もっと良い方法がありそう……)。
最後に
あとは、Markdownファイル内で、広告を表示したい場所に <!--ad-->
と入力します。
以上です。