Login

Google Analytics Template Tag

Author:
jarofgreen
Posted:
July 28, 2009
Language:
Python
Version:
1.0
Score:
4 (after 7 ratings)

Includes the Javascript for Google Analytics. Will not show Google Analytics code when DEBUG is on or to staff users.

Use {% googleanalyticsjs %} in your templates.

You must set something like

GOOGLE_ANALYTICS_CODE = "UA-1234567-1"

in your settings file.

Assumes 'user' in your template variables is request.user, which it will be if you use:

return render_to_response('template.html',{ }, context_instance=RequestContext(request))

(Assuming django.core.context_processors.auth is in TEMPLATE_CONTEXT_PROCESSORS, which it is by default)

 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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 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.

#

Please login first before commenting.