Friday, December 11, 2009

Using Google's jQuery CDN with Django when not in development

I wanted to transition the Django site I work with primarily to use Google's jQuery CDN. However, when developing locally, it's often faster to just use a local copy. What I wanted was a way to toggle which copy of jQuery was being used based on the environment.

Environment Detection
Before we can toggle the jQuery location, we need to have a way to detect which environment we're running in.I previously blogged about how I have my configured. There are different ways to do this. One is to use, the other is to have conditional code in your main which determines values. Either way works.

As for my setting, on the webserver is a folder structure that resembles...

My webserver pulls double duty, hosting both a production version ("prod") and a staging/testing version ("devel"). In my file I'm using this to determine which environment Django is running in...
import os
DJANGO_ROOT = os.path.abspath(os.path.dirname(__file__))

# Globals for determining settings

if 'django_devel' in DJANGO_ROOT:
elif 'django_prod' in DJANGO_ROOT:

Most likely, you'll have some other what you're determining your environment. In that case just substitute that.

{% jquery template tag %}
Now that we have the required support code to detect what environment we're running in, putting together the actual implementation is simple.

I decided to go with a template tag. It's simple and easy.
import settings
from django import template
from django.conf import settings

register = template.Library()

# -----------------------------------------------------------------------------
# jQuery
# -----------------------------------------------------------------------------
def jquery(parser, token):
return JQueryNode()

class JQueryNode(template.Node):
def render(self, context):
jquery = ''
jquery_ui = ''
if getattr(settings, 'DEVELOPMENT', True):
media_url = getattr(settings, 'MEDIA_URL', '/media/')
jquery = '%sjs/jquery-1.3.2.min.js' % media_url
jquery_ui = '%sjs/jquery-ui-1.7.2.custom.min.js' % media_url
return '<script type="text/javascript" src="%s"></script><script type="text/javascript" src="%s"></script>' % (jquery, jquery_ui)

There are a couple of things to note here.

First, there's a hard-coded path in this code. Because I plan to always use this template tag every time I need jQuery, I felt confident doing so as it leaves only one place to edit. However, if you won't be following that rigid of an implementation pulling the locations of jQuery out and into a file would probably be a smart idea.

Second, I'm implementing my type of detection for the environment. This probably differs from the majority of Django users.

When all is said and done, all that needs to remain is to simply drop the tag into base.html and we're good to go.
{% load jquery %}{% jquery %}


This comment has been removed by a blog administrator.

  © Blogger template 'Minimalist G' by 2008

Back to TOP