HugoでGoogleAnalytics4を設定する

HugoでGoogleAnalytics4を設定する

October 5, 2024

前提

使用テーマ: hello-friend-ng

config.toml

    [params.author]
        name = "yama.sh"
        description = "<p>If you like a water, you already like 72% of me. </p><p>フルリモートコーポレートエンジニア, 情シス @Kyoto</p>"
 
        googleAnalytics = "G-1459LE635K"

Google tag(載せたいコード)

直接 head.html に記載してもよいが、今回は config.toml から値を持ってこれるようにする。

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-xxxxxxx"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-xxxxxxx');
</script>

実装

head.htmlをlayoutsにコピーする

head.html に Google tag を記載したいので、Hugo のお作法に則りhead.htmlをlayoutsにコピーする
themes/hello-friend-ng/layouts/partials/head.html > layouts/partials/head.htmlhead.html をコピーする。

head.html の中身に下記を追加

<!-- Google Analytics template -->
{{ with .Site.Params.Author.googleAnalytics }}
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id={{ . }}"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', '{{ . }}');
</script>
{{ end }}

with で .Site.Params.Author.googleAnalytics の値が存在すれば実行するようにし、値は {{ . }} で持ってくる。