3

问题是{{ STATIC_URL }}在 django-compressor 编译为 .js 文件的咖啡脚本文件中引用它时没有正确加载。

在我的 django 模板中,我有

//this loads fine
{{ STATIC_URL }}
{% load compress %}
{% compress js %}

//STATIC_URL in here does not load
<script type="text/coffeescript" charset="utf-8" src="/static/stuff.coffee" />  

{% endcompress %}

stuff.coffee我有

$('#test').prepend '<img src="{{ STATIC_URL }}images/image.png" />'

那么浏览器中渲染出来的HTML就是

/static/
<img id="theImg" src="{{ STATIC_URL }}images/image.png">

因此我的问题是,如何让 Django 识别{{ STATIC_URL }}咖啡脚本文件中的 ?非常感谢您的帮助!

4

1 回答 1

3

您的[.js|.coffee]文件不是 django 模板,不会被评估。您需要使用 django 的模板渲染器预处理脚本,或者在 html 模板中设置变量,并将其分配给 javascript 窗口属性。例如:

在您的 Django 模板中:

window.staticUrl = "{{ STATIC_URL }}";

{% load compress %}
{% compress js %}

//STATIC_URL in here does not load
<script type="text/coffeescript" charset="utf-8" src="/static/stuff.coffee" />  

{% endcompress %}

在你的stuff.coffee

$('#test').prepend "<img src="#{window.staticUrl}images/image.png" />"
于 2012-02-15T11:40:39.547 回答