通过django将STATIC_URL传递给文件javascript [英] Passing STATIC_URL to file javascript with django
问题描述
哪些是将{{STATIC_URL}}传递给javascript文件的最佳解决方案?
Which is the best solution to pass {{ STATIC_URL }} to javascript files?
我正在使用django和python。
I'm working with django and python.
提前感谢。
请问。
Thanks in advance. Regards.
推荐答案
django-compressor
这个以及通过将您所需的所有JS或CSS集中到一个文件中并优化文件大小来优化您的网站。
django-compressor
lets you do this as well as optimize your site by condensing all of your required JS or CSS into one file and optimizing file size.
更新:默认情况下,压缩器将使用 STATIC_URL
将相对URL转换为绝对URL。如果您下载开发版本,它附带了一个django模板引擎解析器,它可以直接在您的CSS文件中使用所有django模板代码,例如 {%static%}
标签。
UPDATE: By default, compressor will convert relative urls into absolute urls using STATIC_URL
. If you download the development version, it comes with a django template engine parser which lets you use all django template code directly in your CSS files, such as the {% static %}
tag.
https://github.com/jezdez/django_compressor
安装后,在settings.py中启用 TemplateFilter
,以通过模板引擎解析您的js或css文件。 / p>
Enable the TemplateFilter
in settings.py after installing to parse your js or css files via the template engine.
COMPRESS_JS_FILTERS = [
'compressor.filters.template.TemplateFilter',
]
现在, {%compress js%}
块中的任何JS都将由django模板语言解析...
Now any JS within {% compress js %}
blocks will be parsed by the django template language...
{% compress js %}
<script src="/my_script.js" type="text/javascript"></script>
{% endcompress %}
// my_script.js
alert('{{ STATIC_URL|escapejs }}');
你问最好的方法 - 我认为这是最好的。当然比提供动态文件要好。
You asked for the best way -- I think this is the best. Certainly better than serving dynamic files.
这篇关于通过django将STATIC_URL传递给文件javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!