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>
"""
Comments
If google changes something you'll have to restart your server. How is this easier than just adding it to your base template?
#
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.
#
@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.
#
I would just put the analytics html code in a separate template and {% include "analytics.html" %} where ever I need it.
#