Skip to content Skip to sidebar Skip to footer

Django Reverse() For Javascript

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

Solution 1:

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.

Solution 2:

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?

<script>MYGLOBAL.mymodule.init({
    fancy_ajax_url: '{% url fancy %}',
    fancier_ajax_url: '{% url fancier %}'
});
</script>

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.

Solution 3:

I created a mechanism that builds a list of url patterns in your Django project and outputs that in a Javascript file. It is a fork of django-js-utils.

The repo link is here: https://github.com/Dimitri-Gnidash/django-js-utils

Solution 4:

https://github.com/mlouro/django-js-utils

dutils is a small utility library that aims to provide JavaScript/Django developers with a few utilities that will help the development of RIA on top of a Django Backend.

It currently supports the following features:

  • Reverse method for generating Django urls...

Solution 5:

We created a small app called django-js-reverse for this purpose.

For example you can retrieve a named url

urls.py:

url(r'^/betterliving/(?P[-\w]+)/(?P\d+)/$', 'get_house', name='betterliving_get_house'),

in javascript like:

Urls.betterliving_get_house('house', 12)

result:

/betterliving/house/12/

Post a Comment for "Django Reverse() For Javascript"