feat: add google analytics support (#70)

* feat: support google analytics

* docs: add instruction for setting up ga
This commit is contained in:
Xin 2023-09-21 08:03:35 +01:00 committed by GitHub
parent b51bfa3177
commit 4e63aa4f14
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 35 additions and 0 deletions

View File

@ -197,3 +197,12 @@ There are three available options: `full`, `wide`, and `normal`.
By default, the page width is set to `normal`.
Similarly, the width of the navbar and footer can be customized by the `params.navbar.width` and `params.footer.width` parameters.
### Google Analytics
To enable Google Analytics, set the `googleAnalytics` parameter in the config file:
```yaml {filename="hugo.yaml"}
googleAnalytics: G-XXXXXXXXXX
```

View File

@ -7,6 +7,8 @@ enableGitInfo: true
# enableEmoji: false
hasCJKLanguage: true
# googleAnalytics: G-XXXXXXXXXX
outputs:
home: [HTML]
page: [HTML]

View File

@ -0,0 +1,13 @@
{{ with .Site.GoogleAnalytics }}
<!-- Global site tag (gtag.js) - Google Analytics -->
<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 }}

View File

@ -16,10 +16,21 @@
{{ end -}}
</title>
<meta name="description" content="{{ partial "utils/page-description.html" . }}" />
{{ partial "opengraph.html" . }}
{{ template "_internal/schema.html" . -}}
{{ template "_internal/twitter_cards.html" . -}}
{{ partialCached "head-css.html" . }}
<!-- Google Analytics -->
{{- if and .Site.GoogleAnalytics (eq hugo.Environment "production") }}
<link rel="preconnect" href="https://www.googletagmanager.com" crossorigin />
{{ partial "google-analytics.html" . }}
{{- end }}
<script>
/* Initialize light/dark mode */
if (localStorage.getItem("color-theme") === "dark" || (!("color-theme" in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches)) {