Google Analytics Templatetag

 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
34
35
36
from django import template
from django.conf import settings

from django.template import Context, loader

register = template.Library()

@register.simple_tag
def analytics():
    'You must define ANALYTICS_ID = "UA-XXXXXXX-X" in your settings.py'

    analytics_id = getattr(settings, 'ANALYTICS_ID', None)
    if analytics_id.strip() != '':
        t = loader.get_template ('analytics/analytics_template.html')
        c = Context({
            'analytics_code': analytics_id,
        })
        return t.render(c)

    else:
        return ""


"""
in templates/analytics/analytics_html.  paste the following

<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">
var pageTracker = _gat._getTracker("{{ analytics_code }}");
pageTracker._trackPageview();
</script>

"""

More like this

  1. Google Analytics Template Tag by jarofgreen 3 years, 9 months ago
  2. Google Analytics noscript tracking by ganzogo 2 years, 3 months ago
  3. Google Analytics Template Tag by blinks 5 years, 6 months ago
  4. Private Context Decorator by acdha 3 years, 9 months ago
  5. {% with %} template tag by SmileyChris 6 years, 1 month ago

Comments

dnordberg (on October 9, 2008):

If google changes something you'll have to restart your server. How is this easier than just adding it to your base template?

#

Arien (on October 9, 2008):

These tags don't change that often, anyway. But if you are concerned about that, you could do a simple include of a generic file and keep the Google code in it :)

I think this can serve for similar things though, not just Google Analytics. Thanks for the idea.

#

rizumu (on October 9, 2008):

@dnordberg, I agree and don't want to restart the server either. I updated the tag to pull from the html in from a template file. BTW, this is an adaptation of a few snippets I found around, but I wanted the tag to work a little differently, and with the updated codes.

#

hasenj (on October 12, 2008):

I would just put the analytics html code in a separate template and {% include "analytics.html" %} where ever I need it.

#

(Forgotten your password?)