Django reverse() for JavaScript

前端 未结 9 1030
情深已故
情深已故 2020-12-24 07:24

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

9条回答
  •  有刺的猬
    2020-12-24 08:00

    First, you should name your url:

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

    Then you could pass urls as variables to your module:

    
    
    
    // js/my-module.js
    var MyModule = {
        init: function(url) {
            console.log(url);
        }
    };
    

    You could use tokens in your url:

    
    
    
    // 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();
    });
    

提交回复
热议问题