Django reverse() for JavaScript

dir01 picture dir01 · Nov 25, 2009 · Viewed 14.6k times · Source

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'),

Answer

kodmasin picture kodmasin · Oct 16, 2011

Try creating javascript helper functions (in django template) for generating url string. In simple form they could look like this:

function generete_some_url(id){
    return "{% url some_url itemid=112233 %}".replace("112233", id);
}

Maybe this has some other implications but I think it should work.