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)
Comments
You need to access the context to get the current user. Doing this is part of the process needed to add to the context...
So, you can find out how to do it here; http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#setting-a-variable-in-the-context
#
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.
#
edited to add note about django.core.context_processors.auth in TEMPLATE_CONTEXT_PROCESSORS
#
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".
#
Was using a context processor and an if block in my base template, this is a much better solution.
#
instead of:
you should use:
That way is someone is using a settings file other than the default your code will use the correct settings file.
#