feat: add GTM tracking support

This commit is contained in:
Sergey Motornyuk 2023-06-14 18:24:48 +03:00
parent 2a74be2e27
commit 5268985575
4 changed files with 32 additions and 1 deletions

View File

@ -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_
@ -45,6 +45,10 @@ def tracking_mode():
if id_.startswith("G-"):
return "gtag"
if id_.startswith("GTM-"):
return "gtm"
return "ga"

View File

@ -6,6 +6,7 @@ from ckanext.googleanalytics import config
def get_helpers():
return {
"googleanalytics_header": googleanalytics_header,
"googleanalytics_id": googleanalytics_id,
"googleanalytics_resource_prefix": googleanalytics_resource_prefix,
"googleanalytics_tracking_mode": googleanalytics_tracking_mode,
}
@ -43,3 +44,6 @@ def googleanalytics_header():
def googleanalytics_tracking_mode():
return config.tracking_mode()
def googleanalytics_id():
return config.tracking_id()

View File

@ -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 -->

View File

@ -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 %}