Added Google Tag Manager support
authorThierry Florac <thierry.florac@onf.fr>
Wed, 15 Nov 2017 17:02:31 +0100
changeset 240 007e0e70ef13
parent 239 36268865b9bf
child 241 4b68a8759677
Added Google Tag Manager support
src/pyams_skin/extension.py
src/pyams_skin/interfaces/extension.py
src/pyams_skin/viewlet/extension/tagmanager.py
src/pyams_skin/viewlet/extension/templates/tag-manager.pt
--- a/src/pyams_skin/extension.py	Fri Nov 10 13:48:12 2017 +0100
+++ b/src/pyams_skin/extension.py	Wed Nov 15 17:02:31 2017 +0100
@@ -18,7 +18,7 @@
 # import interfaces
 from pyams_skin.interfaces.extension import \
     IGoogleAnalyticsInfo, GOOGLE_ANALYTICS_INFO_KEY, \
-    IUserReportInfo, USER_REPORT_INFO_KEY
+    IUserReportInfo, USER_REPORT_INFO_KEY, IGoogleTagManagerInfo, GOOGLE_TAGS_INFO_KEY
 from pyams_utils.interfaces.site import ISiteRoot
 from zope.annotation.interfaces import IAnnotations
 
@@ -29,6 +29,25 @@
 from zope.schema.fieldproperty import FieldProperty
 
 
+@implementer(IGoogleTagManagerInfo)
+class GoogleTagManagerInfo(Persistent):
+    """Google tag manager settings class"""
+
+    enabled = FieldProperty(IGoogleTagManagerInfo['enabled'])
+    container_id = FieldProperty(IGoogleTagManagerInfo['container_id'])
+    activation_mode = FieldProperty(IGoogleTagManagerInfo['activation_mode'])
+
+
+@adapter_config(context=ISiteRoot, provides=IGoogleTagManagerInfo)
+def GoogleTagManagerInfoFactory(context):
+    """Google Tag Manager settings factory"""
+    annotations = IAnnotations(context)
+    info = annotations.get(GOOGLE_TAGS_INFO_KEY)
+    if info is None:
+        info = annotations[GOOGLE_TAGS_INFO_KEY] = GoogleTagManagerInfo()
+    return info
+
+
 @implementer(IGoogleAnalyticsInfo)
 class GoogleAnalyticsInfo(Persistent):
     """Google Analytics settings class"""
--- a/src/pyams_skin/interfaces/extension.py	Fri Nov 10 13:48:12 2017 +0100
+++ b/src/pyams_skin/interfaces/extension.py	Wed Nov 15 17:02:31 2017 +0100
@@ -36,6 +36,28 @@
 ACTIVATION_MODES = SimpleVocabulary([SimpleTerm(k, title=v) for k, v in ACTIVATION_MODES_LABELS.items()])
 
 
+GOOGLE_TAGS_INFO_KEY = 'pyams_skin.tagmanager_info'
+
+
+class IGoogleTagManagerInfo(Interface):
+    """Google Tag Manager account info"""
+
+    enabled = Bool(title=_("Activate Google Tag Manager?"),
+                   description=_("Is Google Tag Manager activated?"),
+                   required=True,
+                   default=False)
+
+    container_id = TextLine(title=_("Container ID"),
+                            description=_("Google Tag Manager container ID (may start with 'GTM-')"),
+                            required=False)
+
+    activation_mode = Choice(title=_("Activation mode"),
+                             description=_("Mode(s) in which Google Tags are activated"),
+                             vocabulary=ACTIVATION_MODES,
+                             default=ACTIVATED_ON_BOTH,
+                             required=True)
+
+
 GOOGLE_ANALYTICS_INFO_KEY = 'pyams_skin.analytics_info'
 
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_skin/viewlet/extension/tagmanager.py	Wed Nov 15 17:02:31 2017 +0100
@@ -0,0 +1,52 @@
+#
+# Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+
+# import interfaces
+from pyams_skin.interfaces.extension import IGoogleTagManagerInfo, ACTIVATED_ON_FRONT, ACTIVATED_ON_BACK
+from pyams_skin.interfaces.viewlet import IJSExtensionsViewletManager
+from pyams_skin.layer import IPyAMSLayer
+try:
+    from pyams_zmi.layer import IAdminLayer
+except ImportError:
+    IAdminLayer = None
+
+# import packages
+from pyams_template.template import template_config
+from pyams_viewlet.viewlet import viewlet_config, Viewlet
+
+
+@viewlet_config(name='tag-manager', manager=IJSExtensionsViewletManager)
+@template_config(template='templates/tag-manager.pt', layer=IPyAMSLayer)
+class GoogleTagManagerViewlet(Viewlet):
+    """Google Tag Manager viewlet"""
+
+    def __new__(cls, context, request, view, manager):
+        info = IGoogleTagManagerInfo(request.root)
+        if not info.enabled:
+            return None
+        if IAdminLayer is None:
+            if info.activation_mode == ACTIVATED_ON_BACK:
+                return None
+        else:
+            if ((info.activation_mode == ACTIVATED_ON_FRONT) and IAdminLayer.providedBy(request)) or \
+               ((info.activation_mode == ACTIVATED_ON_BACK) and not IAdminLayer.providedBy(request)):
+                return None
+        return Viewlet.__new__(cls)
+
+    @property
+    def config(self):
+        return IGoogleTagManagerInfo(self.request.root)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_skin/viewlet/extension/templates/tag-manager.pt	Wed Nov 15 17:02:31 2017 +0100
@@ -0,0 +1,17 @@
+<!-- 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', '<tal:var content="view.config.container_id" />');
+</script>
+<!-- End Google Tag Manager -->