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 1 year ago
  2. Google Analytics Templatetag by rizumu 3 years, 3 months ago
  3. Google Analytics Template Tag by blinks 4 years, 3 months ago
  4. Mobile browser detection middleware by pavl 1 year, 9 months ago
  5. Template Query Debug by insin 4 years, 11 months ago

Comments

dougal (on July 28, 2009):

You need to access the context to get the current user. Doing this is part of the process needed to add to the context...

So, you can find out how to do it here; http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#setting-a-variable-in-the-context

#

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.

#

(Forgotten your password?)