Publishing service endpoint uri to javascript
My application is made up of two main pieces: 1) an ajax client, and 2) backend services supplying data to the ajax client. Django delivers html files that bootstrap the javascript client, which in turns calls back to Django's restful services. Most of javascript code is in static .js files that being delivered to the browser bypassing Django. When calling back into Django, I started by embedding call endpoints into the javascript code. Soon, I noticed, though, that every time I adjusted an endpoint's url in urls.py, I also had to remember to go back and adjust the javascript. This was suboptimal and violated the DRY principle. I realized that all the information I needed was already in urls.py. All that needed to be done, was to find a way to expose that information to the javascript environment. The code I'm including does exactly that. It consists of two pieces: a view function and a corresponding javascript template. The view function will go through all declared urls looking for those whose name ends with '-svc'. These urls are then converted into javascript constants by the template. The url names are slightly mangled to conform to javascript identifier conventions and if you have any url parameters, they will be encoded into something that javascript can easily replace with real values at run time. For example, `url('^blog/(?P<id>[\d]+/$', 'sample.views.showblog', name='blog-entry')` will become `svc.__BLOG_ENTRY = "/blog/{id}/"` to get the uri from your javascript code, you simply make this call: `svc('BLOG_ENTRY', {id: 12345})` and you'll get back `/blog/12345/` Requirements: the javascript template assumes availability of the Namespace library by Maxime Bouroumeau-Fuseau (http://code.google.com/p/namespacedotjs/)
- javascript
- urls
- url
- service
- endpoint