Skip to content

Instantly share code, notes, and snippets.

@pygeek
Created December 20, 2012 18:09
Show Gist options
  • Save pygeek/4347367 to your computer and use it in GitHub Desktop.
Save pygeek/4347367 to your computer and use it in GitHub Desktop.
# Usage: # Define GOOGLE_ANALYTICS_CODE in your settings. # In your base template put: {% google_analytics %} Python 3 compatible ;-]
rom django import template
from django.conf import settings
register = template.Library()
# Usage:
# Define GOOGLE_ANALYTICS_CODE in your settings.
# In your base template put: {% google_analytics %}
@register.simple_tag
def google_analytics():
code = getattr(settings, "GOOGLE_ANALYTICS_ID", False)
debug = getattr(settings, "DEBUG", False)
if not code:
return "<!-- Goggle Analytics not included because no Google Analytics ID is defined -->"
if not debug:
return "<!-- Goggle Analytics not included because server is running in debug mode -->"
return """
<script type="text/javascript">
var _gaq = _gaq || [];
var pluginUrl =
'//www.google-analytics.com/plugins/ga/inpage_linkid.js';
_gaq.push(['_require', 'inpage_linkid', pluginUrl]);
_gaq.push(['_setAccount', '{0}']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
""".format(code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment