Hugo

Adding GTM using Cupper Theme

Hi,

I am an amateur developer. I really know HTML and CSS and a little JS. I am trying to add a Google Tag manager container to my website, but can’t figure out how to add it without adding it to every single page manually.

Do I just need to add it to the baseof.html file?. Or is there more I should be doing?

I am using the Cupper Theme.

I have implemented this on a heavily modified inkblotty theme.

Create two partial files called…

google_tag_manager_noscript.html

{{ if and ($.Site.Params.google_tag_manager) (not (.Site.IsServer)) }}
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id={{ $.Site.Params.google_tag_manager }}"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
{{ end }}

google_tag_manager.html

{{ if and ($.Site.Params.google_tag_manager) (not (.Site.IsServer)) }}
  <!-- Google Tag Manager -->
  <!-- create dataLayer -->
  <script>
   <!-- OPTIONAL dataLayer -->
    var dataLayer = window.dataLayer = window.dataLayer || [];
    dataLayer.push({
      page:'{{ .Title }}',
      categories:'only examples about your dataLayer'
    });
  </script>
  <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=
  'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  })(window,document,'script','dataLayer','{{ $.Site.Params.google_tag_manager }}');</script>
  <!-- End Google Tag Manager -->
{{ end }}

Add the following line to head.html below charset

{{ partial "google_tag_manager.html" . }}

on your config.toml add your GTM ID like the following to your yaml/toml file under [Params]

google_tag_manager = "GTM-XXXXXXX"

Thank you! I will try this and see if it works.