Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for GTM environments and minor refactoring #3

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 28 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,33 @@
# GTM-integration-Hugo
Google Tag Manager integration for Hugo static websites
Google Tag Manager integration for Hugo static websites, with inspiration and initial code kindly borrowed from Martijn van Vreeden. Please read his blog post on the topic for reference: [How to add Google Tag Manager to a Hugo static website](https:///martijnvanvreeden.nl/how-to-add-google-tag-manager-to-hugo-static-website/)

Please read the detailed instruction on how to implement on my blog: [How to add Google Tag Manager to a Hugo static website](https:///martijnvanvreeden.nl/how-to-add-google-tag-manager-to-hugo-static-website/)
## Installation
Merge this repo with your Hugo folder structure (either as a submodule or manually). Adjust paths if required.

In the layout/template file/partial of the site's `<head>` section add the following lines, preferably directly underneath the `meta charset` tag:

```
{{- if eq .Site.Params.gtm_datalayer "basic"}}{{ partial "gtm-datalayer.html" . }}{{ end }}
{{ if .Site.Params.gtm_id}}{{ partial "gtm-js.html" . }}{{ end }}
```

For the second GTM (noscript) snippet (for browsers with disabled/blocked javascript), add the following Hugo code directly underneath the opening `<body>` tag of your site's template/partial file:

```
{{ if not .Site.IsServer}}{{ if .Site.Params.gtm_id}}{{ partial "gtm-noscript.html" . }}{{ end }}{{ end }}
```

Note that this snippet by default is disabled when in Hugo's server mode (during development), feel free to adjust if needed.

## Updates:

* 04-05-2021: Included additional site param to manage a custom endpoint for Server Side GTM "gtm_endpoint"
### `15-12-2022`
- Add support for [Simo Ahava's excellent ssGTM GTM Loader client template](https://github.com/gtm-templates-simo-ahava/gtm-loader) which allows for changing the gtm.js library name and removing the GTM-XXXXXX id from the GTM snippet if configured in the ssGTM client settings.
- Fix incorrect hugo shortcodes references in README
- Separate datalayer code into separate file for easier management

### `26-06-2022`
- Add support for one GTM environment (for staging/development), which activates when `HUGO_ENVIRONMENT <> production`

### `04-05-2021`
- Include additional site parameters to manage a custom endpoint for Server Side GTM "gtm_endpoint"
19 changes: 19 additions & 0 deletions config/_default/params.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Google Tag Manager Container Details
gtm_id = "GTM-FTR4X67" # enter GTM container ID in format "GTM-XXXXXX". This value is invalidated and redundant if the 'override_container_id' parameter below is set to true
gtm_datalayer = "basic" # set to "basic" to push page metadata into the dataLayer upon page load. Set to other value or blank to disable.

# OPTIONAL - Server-side GTM Settings
gtm_endpoint = "" # enter hostname of GTM server-side endpoint in format sub.domain.tld. If using standard GTM leave blank: ""

# OPTIONAL - Simo Ahava's GTM Loader server-side client template (https://github.com/gtm-templates-simo-ahava/gtm-loader)
use_custom_library_name = false # If this is set to true, ensure to set the gtm_library_name variable below and configure the GTM Custom Loader client template inside your ssGTM container
gtm_library_name = "gtm.js" # if using Simo Ahava's GTM Loader template to enable changing the name of the GTM library, set the document name here (e.g. mylibrary.js) and match it in the client settings online.
override_container_id = false # Set this to true if the GTM Loader client is configured to "Override Container ID" where you have added matched your preferred GTM container ID.

# OPTIONAL - Google Tag Manager Staging Environment
# create an additional "environment" from within the GTM Admin interface meant for "Staging"
# extract the 'gtm_auth' and 'gtm_preview' query parameters from the 'src' URL query in the provided GTM snippet
# this gtm environment snippet activates whenever the HUGO_ENVIRONMENT variable is not set to 'production' (such as running the hugo server)) and the `use_staging_gtm_environment` is set to true.
use_staging_gtm_environment = false
gtm_env_param_gtm_auth = "" # enter `gtm_auth` string here e.g. "dhxfPfIIp62NuQfRTdCd1w".
gtm_env_param_gtm_preview = "" # enter `gtm_preview` string here e.g. "env-8". Leave blank ""
24 changes: 24 additions & 0 deletions layouts/partials/gtm-datalayer.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@

<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
{{- if .ExpiryDate}}'pageExpiryDate': '{{ .ExpiryDate.format "2006-01-02" }}',{{- end }}
'pagePublishDate': '{{ .PublishDate.Format "2006-01-02" }}',
'pageModifiedDate': '{{ .Lastmod.Format "2006-01-02" }}',
{{- if eq .Kind "page" }}'pageReadingTimeMinutes': {{ .ReadingTime }},
'pageReadingTimeSeconds': {{- $readTime := mul (div (countwords .Content) 220.0) 60 }}{{- math.Round $readTime}},
'pageWordCount': {{- .WordCount }},
'pageFuzzyWordCount': {{- .FuzzyWordCount }},{{- else }}{{- end }}
'pageKind': '{{ .Kind }}',
'pageId': '{{ with .File }}{{ .UniqueID }}{{ end }}',
'pageTitle': '{{ .LinkTitle }}',
'pagePermalink': '{{ .Permalink }}',
'pageType': '{{ .Type }}',
'pageTranslated': {{ .IsTranslated }},
{{- if .Params.author -}} 'pageAuthor': '{{ if .Params.author -}}{{ .Params.author }}{{- else if .Site.Author.name -}}{{ .Site.Author.name }}{{- end }}',{{- end }}
{{- if .Params.categories}}{{$category := index (.Params.categories) 0}}'pageCategory':'{{ $category }}', {{- end }}
{{- if .Params.tags}}'pageTags':'{{ delimit .Params.tags "|" }}', {{- end }}
{{- if .IsHome }}'pageType2': 'home',{{- else if eq .Kind "taxonomy" }}'pageType2': 'tag',{{- else if eq .Type "page" }}'pageType2': 'page',{{- else }}'pageType2': 'post',{{- end }}
'pageLanguage': '{{ .Language }}'
});
</script>
2 changes: 1 addition & 1 deletion gtm.html → layouts/partials/gtm-js.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,5 @@
{{ if .Site.Params.gtm_id}}<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//{{ if .Site.Params.gtm_endpoint}}{{ .Site.Params.gtm_endpoint }}{{ else }}www.googletagmanager.com{{ end }}/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
'https://{{ if .Site.Params.gtm_endpoint }}{{ .Site.Params.gtm_endpoint }}{{ else }}www.googletagmanager.com{{ end }}/{{ if .Site.Params.use_custom_library_name }}{{ .Site.Params.gtm_library_name }}{{ else }}gtm.js{{ end }}?{{ if .Site.Params.override_container_id }}{{ else }}id='+i+dl+'{{ end }}{{if .Site.Params.use_staging_gtm_environment}}{{ if not hugo.IsProduction }}&gtm_auth={{ .Site.Params.gtm_env_param_gtm_auth }}&gtm_preview={{ .Site.Params.gtm_env_param_gtm_preview }}&gtm_cookies_win=x{{ end }}{{ end }}';f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','{{ .Site.Params.gtm_id }}');</script>{{ end }}{{ end }}
1 change: 1 addition & 0 deletions layouts/partials/gtm-noscript.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<noscript><iframe src="https://{{ if .Site.Params.gtm_endpoint}}{{ .Site.Params.gtm_endpoint }}{{ else }}www.googletagmanager.com{{ end }}/ns.html?id={{ .Site.Params.gtm_id }}{{ if not hugo.IsProduction }}{{if .Site.Params.use_staging_gtm_environment}}&gtm_auth={{ .Site.Params.gtm_env_param_gtm_auth }}&gtm_preview={{ .Site.Params.gtm_env_param_gtm_preview }}&gtm_cookies_win=x{{ end }}{{ end }}" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>