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.
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.
Share Improve this question asked Aug 10, 2012 at 9:32 Thomas KremmelThomas Kremmel 14.8k26 gold badges112 silver badges178 bronze badges 1- No, that variable will be have value runtime when script is run, which django template resolves which building the page (like compile time). – Rohan Commented Aug 10, 2012 at 9:37
3 Answers
Reset to default 20What 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>';
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();
});
You will need to use string formatting in JavaScript to shoehorn the value into the URL client-side. Don't forget to encode it as JSON before using it in JavaScript.