はじめに

GoogleAnalyticsをHugoBlogに導入したいと思ったのでしてみる。

環境

1
Hugo 0.110.0

GoogleAnalyticsのタグの取得

GoogleAnalyticsのプロパティ作成

  1. https://analytics.google.com/ にアクセスする。
  2. 「管理」→「プロパティを作成」を押す。
create-property-1
  1. プロパティを作成するで下記のように入力。
項目設定値
プロパティ名hugo-blog
レポートのタイムゾーン日本
通貨日本円
create-property-2
  1. ビジネスの説明を入力 create-property-3

  2. ビジネス目標の入力 create-property-4

  3. データ収集を開始するで「ウェブ」を選択する create-property-5

  4. ウェブストリームを作成を押し入力する。 create-property-6

  5. タグが出力されるので控える。 create-property-7

これで GoogleAnalyticsの設定は完了

HugoBlogへの導入

custom_head.htmlの作成

Hugoではテーマを直接編集することはなく、基本的に設定を入れることで大体のことはできる。
そのため、Janeではどのようにすると実現できるかを調査したところ、custom_head.htmlを作成していじれば良いということがわかった。

そのため、プロジェクトルート直下の layouts ディレクトリに、 partials ディレクトリを作成し、その後 custom_head.html を作成する。
これで、custom_head.htmlに書き込みを行うことで、 <head>要素にタグを埋め込むことができる。

custom_head.html は下記のように作成した。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{{- if and (not .Site.IsServer) .Site.GoogleAnalytics -}}
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-XXXXXXXX');
</script>
{{- end -}}

theme/jane/layouts/partials/head.html を見ると

1
2
3
4
5
6
7
<!-- Analytics -->
{{- if and (not .Site.IsServer) .Site.GoogleAnalytics -}}
  {{ template "_internal/google_analytics.html" . }}
{{- end -}}

<!-- Custom head -->
{{ partial "custom_head.html" . }}

こんな感じで記述がある。
config.tomlUAタグを書けばいけるのだが、UAタグは廃止されているので、これは使えない。 なので、if の分岐部分を流用し、custom_head.htmlを作成したというのが経緯になる。

というわけで、この状態でデプロイしてみる。

動作確認

デプロイ後にアクセスをし、下記のように「データ収集は有効です」となっていればOK

success-analytics

参考

おわりに

GoogleAnalytics使用したかったので導入してみました。
適度に見てみようと思います。