Randy Tang
Randy Tang

Reputation: 4353

Django: specify file paths in a JavaScript file

I have the following directory structure which follows Django's standard:

/my_site
    /my_site
    /my_app
        /static
            /my_app
                /js
                    a.js
                    b.js
                    c.js
                    d.js

I have no problem specifying the static path in the html:

{% load staticfiles %}
<script src="{% static 'my_app/js/a.js' %}"></script>

However, there are some statements in file a.js as follows:

var WORKER_PATH = 'b.js';
var encoderWorker = new Worker('c.js');
importScripts('d.js');

I was not able to set the paths for b.js, c.js, and d.js correctly (but they all locate in the same directory!). How do I solve the problem?

Upvotes: 0

Views: 1093

Answers (1)

dazedconfused
dazedconfused

Reputation: 1342

Add another <script> tag in your html:

<script language="javascript">
    var js_b = "{% static 'my_app/js/b.js' %}";
    var js_c = "{% static 'my_app/js/c.js' %}";
    var js_d = "{% static 'my_app/js/d.js' %}";
</script>

After that, you can use variable js_b, js_c, and js_d in your a.js JavaScript file, as they'll be strings of static paths of b.js, c.js, and d.js.

You can also get those variables from your view and return them with your RequestContext:

from django.templatetags.static import static

# in your view function
js_b = static('my_app/js/b.js')
js_c = static('my_app/js/c.js')
js_d = static('my_app/js/d.js')
context = {'js_b': js_b, 'js_c': js_c, 'js_d': js_d}
return render_to_response('your_template.html', RequestContext(request, context))

Upvotes: 4

Related Questions