Django reverse() for JavaScript

前端 未结 9 1029
情深已故
情深已故 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 07:53

    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

    0 讨论(0)
  • 2020-12-24 08:00

    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();
    });
    
    0 讨论(0)
  • 2020-12-24 08:04

    You can remove the parameters from the URL, and pass the dynamic parts as query parameters:

      $('#add-choice-button').on('click', function () {
        var thing_id = $(this).closest('.thing').attr('data-item-id');
        $.get('{% url 'addThing' %}?t='+thing_id, function (data) {
          ...
        });
      });
    
    0 讨论(0)
提交回复
热议问题