Populate URLs in Your Javascript with Django

All this Olympics has inspired me. I’ve decided to train for the summer games in Rio and to pursue my hobbies in full force. The former requires me to learn to kayak; the latter, to program, program, program.

I’m building a fun web-app game on top of Django. And I want to make it dance with a little Javascript. I really like that I can look up the URLs of my pages by an internal name in templates using the {% url %} tag, but unfortunately that functionality isn’t available to me inside my static media—particularly, I’d like to be able to reverse look-up URLs in my site’s javascript, but I don’t want to have to render the file each time it gets served.

After hunting around for a while, I figured, “Why not just render to Javascript once, fill in all the links, and be done with it?” So that’s what I did. And it doesn’t take much.

I wrote a custom command called populate_urls that consumes a template (in this case, my Javascript) and spits out the finished product with all the holes filled in by Django and its handy URL resolvers. Then I stash its output in my static directory and pretend the whole thing never happened.

from __future__ import print_function

import sys

from django.core.management.base import BaseCommand
from django.template import Template, Context

class Command(BaseCommand):
from __future__ import print_function

import sys

from django.core.management.base import BaseCommand, CommandError
from django.template import Template, Context

class Command(BaseCommand):
args = ‘
help = ‘Populates the URLs in the template. If no output filename is supplied, renders the template to standard out.’
traceback = True

def handle(self, *args, **options):
if len(args) < 1: raise CommandError("You must supply a template.") with open(args[0], 'r') as templatefile: template = Template(templatefile.read()) context = Context() with sys.stdout if len(args) < 2 else open(args[1], 'w') as output: print(template.render(context), file=output) [/sourcecode]