Skip to content

Commit

Permalink
feat: add GTM tracking support
Browse files Browse the repository at this point in the history
  • Loading branch information
smotornyuk committed Jun 14, 2023
1 parent 2a74be2 commit 5268985
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
6 changes: 5 additions & 1 deletion ckanext/googleanalytics/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def download_handler():


def tracking_mode():
# type: () -> Literal["ga", "gtag"]
# type: () -> Literal["ga", "gtag", "gtm"]
type_ = tk.config.get("googleanalytics.tracking_mode")
if type_:
return type_
Expand All @@ -45,6 +45,10 @@ def tracking_mode():
if id_.startswith("G-"):
return "gtag"

if id_.startswith("GTM-"):
return "gtm"


return "ga"


Expand Down
4 changes: 4 additions & 0 deletions ckanext/googleanalytics/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
def get_helpers():
return {
"googleanalytics_header": googleanalytics_header,
"googleanalytics_id": googleanalytics_id,
"googleanalytics_resource_prefix": googleanalytics_resource_prefix,
"googleanalytics_tracking_mode": googleanalytics_tracking_mode,
}
Expand Down Expand Up @@ -43,3 +44,6 @@ def googleanalytics_header():

def googleanalytics_tracking_mode():
return config.tracking_mode()

def googleanalytics_id():
return config.tracking_id()
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<!-- Google Tag Manager -->
<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','{{googleanalytics_id}}');</script>
<!-- End Google Tag Manager -->
16 changes: 16 additions & 0 deletions ckanext/googleanalytics/templates/page.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{% ckan_extends %}

{% block page %}
{% block googleanalytics_body_script %}
{% if h.googleanalytics_tracking_mode() == "gtm" %}
{% with id = h.googleanalytics_id() %}
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id={{ id }}"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
{% endwith %}
{% endif %}
{% endblock %}

{{ super() }}
{% endblock page %}

0 comments on commit 5268985

Please sign in to comment.