In my project I have a lot of Ajax methods, with external client-side scripts (I don't want to include JavaScript into templates!) and changing URLs is kind of pain for me because I need to change URLs in my Ajax calls manually.
Is there is some way to emulate the behavior of {% url %}
templatetag in JavaScript?
For example, print urlpatterns starting with ^ajax
and later in scripts replace patterns with their actual values?
That's what on my mind, and my question is - are there any common practices to do things like that? Maybe some reusable applications? Also I will be happy to read any advices and relevant thoughts you have.
Update 1: I'm talking about computed URLs, not static ones:
url(r'^ajax/delete/(?P<type>image|audio)/(?P<item_id>\d+)/from/set/(?P<set_id>\d+)/$', 'blog.ajax.remove_item_from_set'),
What's wrong with putting JavaScript in your templates?
You often want to call an initialisation function in your HTML template anyway, so why not pass it an object containing URLs you'll be using?
If you find yourself passing a lot of variable this way, or wanting to use logic in your JavaScript that you do in your HTML templates, then why not render your script through Django's templating engine? Remember, Django templates are not just for HTML documents - often it helps to use templates for plain text, XML, JSON, and yes even JavaScript. Worried about performance? Then cache the result.
We created a small app called django-js-reverse for this purpose.
For example you can retrieve a named url
urls.py:
in javascript like:
result:
https://github.com/mlouro/django-js-utils
Try creating javascript helper functions (in django template) for generating url string. In simple form they could look like this:
Maybe this has some other implications but I think it should work.
What I usually do is put the URL in either an
<input type="hidden" />
element, or in therel=""
attribute.Then, when writing the JS (using jQuery below) I do:
Nonstandard attributes are well supported by all major browsers and hidden elements don't have to be in forms.
You can remove the parameters from the URL, and pass the dynamic parts as query parameters: