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