Django reverse() for JavaScript

2019-02-01 04:08发布

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

9条回答
贼婆χ
2楼-- · 2019-02-01 04:30

First, you should name your url:

url(r'^blog/(?P<item_id>\d+)/$', 'blog.ajax.remove_item', name='blog-item'),

Then you could pass urls as variables to your module:

<script src="{{ STATIC_URL }}js/my-module.js"></script>
<script>
$(function(){
    MyModule.init('{% url blog-item item.id %}');
});
</script>
// js/my-module.js
var MyModule = {
    init: function(url) {
        console.log(url);
    }
};

You could use tokens in your url:

<script src="{{ STATIC_URL }}js/my-module.js"></script>
<script>
$(function(){
    MyModule.init("{% url blog-item item_id='0000' %}");
});
</script>
// js/my-module.js
var MyModule = {
    init: function(url) {
        var id = 1;
        this._url = url;
        console.log(this.url(id));
    },
    url: function(id) {
        return this._url.replace('0000', id);
    }
};

Notice that your token should match the regex type to resolve successfully (I can't use {item_id} as token because it's defined with \d+).

I was a little bit unsatisfied with this solution and I ended by writing my own application to handle javascript with django: django.js. With this application, I can do:

{% load js %}
{% django_js %}
{% js "js/my-module.js" %}
// js/my-module.js
var MyModule = {
    init: function() {
        var id = 1;
        console.log(Django.url('blog-item', id));
    }
};

$(function(){
    MyModule.init();
});
查看更多
等我变得足够好
3楼-- · 2019-02-01 04:33

I have found this cool django app called Django JS reverse

https://github.com/ierror/django-js-reverse

If you have a url like

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

Then you do

Urls.betterliving_get_house('house', 12)

The result is

/betterliving/house/12/
查看更多
啃猪蹄的小仙女
4楼-- · 2019-02-01 04:36

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

查看更多
登录 后发表回答