django - 引用模板中的静态文件
我有由网页设计应用程序(axure)设计的 django 应用程序的模板。因此,这些模板文件中的所有静态文件引用都是相对的,例如
<img src="/resources/image/icon.gif"/>
我按照此处的说明 https://docs.djangoproject.com/en/dev/howto/static-files/ 修改应用程序的设置以包含静态文件并修复 STATIC_URL。但是,这样一来,我仍然必须将此标记 {{ STATIC_URL }}
放在每个静态文件引用的前面。
有没有一种通用的方法可以让 django 接受这些静态文件的相对路径?
谢谢你!
I have the templates for my django app designed by a web design app (axure). So all the static files reference in these template files are relative, such as
<img src="/resources/image/icon.gif"/>
I followed the instruction here https://docs.djangoproject.com/en/dev/howto/static-files/ to modify the settings for the app to include static files and have STATIC_URL fixed. However, by that way, I still have to put this token {{ STATIC_URL }}
in front of every static files reference.
Is there a generic way to do it that makes django to accept these relative paths to static files?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是“相对”路径。这就是所谓的“相对绝对”。当您在前面添加
/
时。它告诉浏览器直接从域引用以下路径。这与姜戈无关。它与浏览器有关,并且它们都都是这样工作的。{{ STATIC_URL }}
没有什么特别的;这只是一种简单而安全的方法,可以用正确的路径为静态文件的引用添加前缀。实际上,您可以在 HTML 中硬编码完整的 URL:但是如果您的 STATIC_URL 发生了更改,那么您就不走运了。这就是为什么你使用
{{ STATIC_URL }}
,这样无论它设置为“/static/”还是“http://cdn.someprovider.com/myproject/something-else/static/ “你的参考文献总是有效的。长话短说,不,没有“通用方法”。您必须告诉浏览器在哪里可以找到该文件,这需要使用
{{ STATIC_URL }}
。That's not a "relative" path. It's what's called "relative absolute". When you prepend with
/
. It tells the browser to reference the following path directly from the domain. This has nothing to do with Django. It has to do with the browser, and they all work that way.There's nothing special about
{{ STATIC_URL }}
; it's just an easy and safe way to prefix your references to static files with the right path. You could actually hard-code the full URL in the your HTML:But if your STATIC_URL ever changed, you'd be out of luck. That's why you use
{{ STATIC_URL }}
, so that no matter whether it's set to "/static/" or "http://cdn.someprovider.com/myproject/something-else/static/" your references always work.Long and short, no, there's no "generic way". You have to tell the browser exactly where it can find the file, and that requires using
{{ STATIC_URL }}
.如果您使用像 nginx 这样的后端,您可以将 /staticimage 设置为指向 /path/to/static/resources/image/,然后使用 /staticimage。
我确信您使用的任何网络服务器都可以得到这样的路径映射。
If you are using a backend like nginx you could set your /staticimage to point to /path/to/static/resources/image/ and then use /staticimage.
I'm sure any web server you are using can be given such a path mapping.