简体   繁体   English

Javascript和Django'静态'模板标签

[英]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 . 我有一个小网站设置播放一些声音,其列表由我的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. 不是最好的解决方案 - html模板还创建了一堆用于播放声音的按钮和内容,我的Javascript在点击功能中引用了这些按钮和内容。 I'm also using the Javascript Howler library to simplify the playing of the sounds. 我也在使用Javascript咆哮库来简化声音的播放。

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' %}"] . 现在,当我在本地测试它时,它工作得很好,但是在我部署之后,在src: ["{% static 'audio/"+sound+".mp3' %}"]行出现了一个问题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. 这似乎是奇怪的执行,因为它不是将声音插入Django标签并将其作为一个字符串执行,而是似乎执行它: src: ["{% static 'audio/%22%2Bsound%2B%22.mp3' %}"] ,即尝试解析"+作为字符串的一部分。

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. 此外,任何有关如何使这个过程更好的反馈(也许不使用Javascript中的模板标签,感觉不对)将非常感激,但实际上我只是想找到任何方法将此sound值传递给标签在Javascript中。

The Django tags are evaluated by the server whilst the javascript is evaluated by the client browser. Django标签由服务器评估,而javascript由客户端浏览器评估。 As a result the sound variable has not yet been determined when the static tag is executed. 结果,在执行static标签时尚未确定sound变量。

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. 您可以采用的一种方法是使用Django模板循环遍历sounds并将每个静态引用存储在JSON字典中。 Then your javascript could lookup the required value from that: 然后你的javascript可以从中查找所需的值:

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

...

src: [my_references[sound]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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