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
This is the `local_settings.py` trick extended to Django templates.
Sometimes you need to insert some arbitrary code in the HTML of the production site for external service integration like uservoice, typekit, google analytics... You don't want to put this code into source control because some other sites using the same source code may not need it.
So, add this template tag to your collection and do:
{% try_to_include 'head.html' %}
And leave `head.html` out of source control. Then when you need to include some code on your production site, just add the `head.html` template with the desired code to include.
I usually have one included template in the header for extra `<head>` tags, and one in the footer for extra javascript.
Node that the included template is rendered against the current context. If the template doesn't exist, an empty string is returned.
Also see the [full blog post](http://bruno.im/2009/dec/07/silently-failing-include-tag-in-django/) about this tag.
- templatetag
- include
- silent