简体   繁体   中英

Javascript and the Django 'static' template tag

I've got a wee site set up to play some sounds a list of which are passed forward by my view . I'm going to go straight into the code:

var sounds = "{{js_sounds|escapejs}}";
sounds = JSON.parse(sounds);
var howls = {};

sounds.forEach(function(sound){
    howls[sound] = new Howl({
        src: ["{% static 'audio/"+sound+".mp3' %}"]
    });

    $(document).on('click', '#'+sound+'_btn_play', function(){
        howls[sound].play();
    });
    $(document).on('click', '#'+sound+'_btn_stop', function(){
        howls[sound].stop();
    });
}

Not the neatest solution - the html template also creates a bunch of buttons and things for playing the sounds, which my Javascript references in those on click functions. I'm also using the Javascript Howler library to simplify the playing of the sounds.

Now, when I was testing this locally it worked perfectly, but after I deployed, a problem arose in the line src: ["{% static 'audio/"+sound+".mp3' %}"] . It seems like this is being executed weirdly, because rather than inserting the sound into the Django tag and executing it as one string, it seems to be executing it as: src: ["{% static 'audio/%22%2Bsound%2B%22.mp3' %}"] , ie attempting to parse the "+ as part of the string.

I'm struggling to figure out why it's doing this when deployed but not locally. Also, any feedback on how to make this process better (perhaps not using template tags in Javascript, that doesn't feel right) would be much appreciated, but really I'm just looking for any way to pass this sound value to the tag in Javascript.

The Django tags are evaluated by the server whilst the javascript is evaluated by the client browser. As a result the sound variable has not yet been determined when the static tag is executed.

One approach you could take is to iterate through sounds using a Django template for loop and store each static reference in a JSON dictionary. Then your javascript could lookup the required value from that:

var my_references = {
{% for sound in sounds %}
    "{{ sound }}":"{% static 'audio/"+sound+".mp3' %}",
{% endfor %}
};

...

src: [my_references[sound]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM