Notice This is a beta feature offered by Google. Also this is automatic translation, which means the results are often inacurate and/or hilarious. Enjoy.

ARCHIVES / RSS
Blog

Google Analytics for Django revisited.

h3  ~  30 Nov 2007, 03:33  –  post a comment

I've posted a while ago a small simple tag snippet for Django to allow easy inclusion of the Google Analytics tracker in a template with something like this;

"{%google_analytics 'TRACKER-CODE' %}".

The code was working fine but we still had one small problem, we had to constantly comment/uncomment it when switching from development to production. A repetitive task that any programmer with an ounce of respect for himself will soon get bored to do.

So I patched it to execute urchinTracker() only if the current window location contains a IP followed by a port number, by putting _uacct="%s";urchinTracker(); in a if statement like this:

if(!!!window.location.href.match(/http://d+.d+.d+.d+:d+/)) {
    _uacct="tracker-code";urchinTracker();
}

NOTE: The triple "!" isn't a "not not not" statement as my co-worker though. It's a not statement followed by double exclamation. In JavaScript the double exclamation converts any value to boolean, a primitive kind of typecasting I guess. It was useful in this context because the match method returns null or an array.

I've tried to include the Google script tag conditionally with DOM insertion, But I forgot this idea because I got a script error. The urchinTracker() was called before the script was fully loaded, and I didn't want to use a timeout.

Here is the actual python code:

@register.simple_tag
def google_analytics(key):
    '''
    Return the Google Analytics HTML code. 
    *key* (required): your Google API key
    '''
    return '<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script><script type="text/javascript">' 
           'if(!!!window.location.href.match(/http://d+.d+.d+.d+:d+/)) {' 
           '_uacct="%s";urchinTracker();}</script>' % key

Once again JavaScript saved the day.

post a comment Comments

no comments :|

Copyrighted stuff .. u know.