Google Analytics Template Tag

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from django import template
import settings
register = template.Library()


class ShowGoogleAnalyticsJS(template.Node):
	def render(self, context):
		code =  getattr(settings, "GOOGLE_ANALYTICS_CODE", False)
		if not code:
			return "<!-- Goggle Analytics not included because you haven't set the settings.GOOGLE_ANALYTICS_CODE variable! -->"

		if 'user' in context and context['user'] and context['user'].is_staff:
			return "<!-- Goggle Analytics not included because you are a staff user! -->"

		if settings.DEBUG:
			return "<!-- Goggle Analytics not included because you are in Debug mode! -->"

		return """
		<script type="text/javascript">
			var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
			document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
		</script>
		<script type="text/javascript">
			try {
			var pageTracker = _gat._getTracker('""" + str(code) + """');
			pageTracker._trackPageview();
		} catch(err) {}</script>
		"""

def googleanalyticsjs(parser, token):
	return ShowGoogleAnalyticsJS()

show_common_data = register.tag(googleanalyticsjs)

More like this

  1. Google Analytics noscript tracking by ganzogo 3 years, 2 months ago
  2. Google Analytics Template Tag by blinks 6 years, 5 months ago
  3. Strip Google Analytics cookies for caching middleware purposes by nf 4 years, 5 months ago
  4. Google Analytics Templatetag by rizumu 5 years, 6 months ago
  5. Silently-failing include tag by brutasse 3 years, 10 months ago

Comments

jarofgreen (on July 28, 2009):

I've done that before to, don't know why I didn't think of it this time :-) Edited to fix. Also returned the google js to it's original form.

#

jarofgreen (on July 30, 2009):

edited to add note about django.core.context_processors.auth in TEMPLATE_CONTEXT_PROCESSORS

#

ethanpoole (on August 14, 2010):

This code snippet works great, but I just have to point out the comments when the Analytics code is excluded always says "Goggle" instead of "Google".

#

chriszweber (on January 17, 2012):

Was using a context processor and an if block in my base template, this is a much better solution.

#

brousch (on February 17, 2012):

instead of:

import settings

you should use:

from django.conf import settings

That way is someone is using a settings file other than the default your code will use the correct settings file.

#

(Forgotten your password?)