Roronoa Zoro
Roronoa Zoro

Reputation: 1013

Django: Variables inside static tag

The question here seems to be very similar to mine; however, I tried what was suggested there but it did not work in my case so perhaps my question is different after all.

In my html file (in the <script></script> for the Javascript section), I have:

var snd = new Audio("{% static 'updateMap/cual_es_su_nombre.mp3' %}");
snd.play();

which plays the mp3 just fine; however, I would like to be able to replace the file name: cual_es_su_nombre.mp3 with a variable. I am getting the file name(s) from the server.

So, the first thing that I do is to load the file names into a Javascript array:

var all_file_names = new Array();
{% for item in all_file_names_from_server %}
    all_file_names.push("{{ item |safe }}");
{% endfor %}

Then, ultimately, I would like to be able to do this for example:

var snd = new Audio("{% static 'updateMap/'|add:all_file_names[0] %}");
snd.play();

However, that does not work...

Upvotes: 2

Views: 2562

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37364

The Django template engine will have completely finished rendering the page before passing it to the browser. You can use it to write Javascript, but you can't access it from Javascript or in ways that depend on Javascript data structures. I think your best bet would be to build an array of the resolved static URLs rather than just an array of the filenames (possibly instead of that array if you don't need both). Something like:

var all_file_names = new Array();
{% for item in all_file_names_from_server %}
    all_file_names.push("{{ item |safe }}");
    all_file_uris.push("{% static 'updateMap/'|add:item|safe %}");
{% endfor %}

Then:

var snd = new Audio(all_file_uris[0]);
snd.play();

Upvotes: 3

Related Questions