Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Use Javascript variable in URL reverse call as parameter

is there a way to use a .js variable as a parameter in a Django template url reverse call? The approach below does not work, which is not very surprising:

"fnRender": function ( o, val ) {
     return '<a href="{% url update_task o.aData[0] %}">' + o.aData[1]  +'</a>';
}

I know that I could pass the needed data via the Django view, but unfortunately I have to use the data from the .js library.

like image 963
Thomas Kremmel Avatar asked Aug 10 '12 09:08

Thomas Kremmel


2 Answers

What I usually do is pass some sort of default parameter into the URL in the template, which acts as a sentinel which I can then replace dynamically in the Javascript. Something like:

var url = '{% url update_task "foobarbaz" %}';
url = url.replace('foobarbaz', o.aData[0]);
return '<a href="' + url + '">' + o.aData[1]  +'</a>';

 

like image 130
Daniel Roseman Avatar answered Oct 16 '22 08:10

Daniel Roseman


You could pass urls as variables to your module:

<script src="{{ STATIC_URL }}js/my-module.js"></script>
<script>
$(function(){
    MyModule.init('{% url my_url %}');
});
</script>
// js/my-module.js
var MyModule = {
    init: function(url) {
        doSomething(url);
    }
};

or with many

<script src="{{ STATIC_URL }}js/my-module.js"></script>
<script>
$(function(){
    MyModule.init({
        my_url: '{% url my_url %}',
        other_url: '{% url other_url "param" %}'
    });
});
</script>
// js/my-module.js
var MyModule = {
    init: function(options) {
        var my_url = options.my_url,
            other_url = options.other_url;

        doSomething(my_url);
    }
};

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 my_url = Django.url('my_url'),
            other_url = Django.url('other_url','param'),
            my_static_file = Django.file('some-file.json');

            doSomething(my_url);
    },
    other: function(param) {
        $.get(Django.url('other_url', param), {urlParam: 'urlParam'}, function(data) {
            doSomethingElse(data);
        });
};

$(function(){
    MyModule.init();
});
like image 43
noirbizarre Avatar answered Oct 16 '22 10:10

noirbizarre