Django - 引用模板中的静态文件

问题描述 投票:9回答:3

我在模板中引用静态文件时遇到了困难。我正在使用Twitter Bootstrap并将引导程序文件(css,img,js)放在mysite / static中。

我根据STATIC_URL设置了STATIC_ROOTTEMPLATE_CONTEXT_PROCESSORSthis tutorial。我运行了./manage.py collectstatic,复制了72个文件。我还将以下模板标记添加到我的模板(index.html)文件中,但这没有用。

{% load staticfiles %}
<link rel="stylesheet" href="{% static user_stylesheet %}" type="text/css" media="screen"/>

任何有关如何引用文件的帮助,以便引导程序样式返回到模板将非常感谢!

python django templates twitter-bootstrap static
3个回答
16
投票

它应该是

{% load static from staticfiles %}

然后是类似的东西

<!-- path -->
<link href="{% static 'bootstrap/css/bootstrap.css' %}" rel="stylesheet" type="text/css">
<!--->

更新完整性

文件夹结构

  • PROJ APP1 APP2 myproj_public 静态的 CSS bootstrap.css JS xyz.js

设置文件

STATIC_ROOT = os.path.join(os.path.abspath(
    os.path.join(PROJECT_ROOT, 'myproj_public', 'static')), '')

STATIC_URL = '/static/'

4
投票

您是否在视图中设置了user_stylesheet上下文变量?您需要先设置它,然后才能将其传递给模板。

我通常只使用{{ static_url }}标签来做这些事情,所以我的代码包括bootstrap组件就像。

<link href="{{ STATIC_URL }}bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="{{ STATIC_URL }}bootstrap/js/jquery.js"></script>

假设bootstrap文件夹存在于静态内部。

编辑

对于你的情况,要设置user_stylesheet上下文变量,你需要做类似的事情

dict["user_stylesheet"]= <path to your file>
#add other context variables you might have to
render_to_response(<your template name>, dict, context_instance=RequestContext(request))

0
投票

设置static_root时,例如:

STATIC_ROOT = os.path.join(BASE_DIR, "static_root/")

,所有文件都复制到那里,而不是在project_root/static。它是Django 1.3中引入的一种新机制,用于简化静态文件处理:它将收集每个STATICFILES_DIR中的所有文件以及每个已安装应用程序下的所有static目录,因此您可以一次性复制它们。

请使用static_root路径引用css / js文件。

© www.soinside.com 2019 - 2024. All rights reserved.