简体   繁体   English

Django 模板:应用目录中的 static 文件

[英]Django template: static files in app directory

In Django settings.py file we have在 Django settings.py文件中,我们有

STATIC_URL = '/static/'

And in each app directory I have static folder for css, js files.在每个应用程序目录中,我都有 static 文件夹,用于 css、js 文件。

For example:例如:

├── myapp
│   ├── migrations
│   ├── __pycache__
│   ├── static
│   └── templates

When I use {% static "......." %} in *.html file当我在 *.html 文件中使用{% static "......." %}

For example例如

  <link rel="stylesheet" href="{% static "style/fesahat.css" %}" />
  <link rel="stylesheet" href="{% static "style/loginStyle.css" %}" />

In output render django creates URL like this:在 output 渲染中 django 像这样创建 URL :

mysite.com/static/style/fesahat.css
mysite.com/static/style/loginStyle.css

I want to create the URL like this:我想像这样创建 URL:

mysite.com/myapp/templates/static/style/fesahat.css
mysite.com/myapp/templates/static/style/loginStyle.css

No you don't.不,你没有。 Static files are not templates;静态文件不是模板; don't put them there.不要把它们放在那里。

@Daniel Roseman is right. @丹尼尔罗斯曼是对的。 Always use meaning full names.始终使用有意义的全名。

STATIC_URL = '/static/' #This is URL prefix so use any prefix

Always use name-spacing in each app level static directory.始终在每个应用程序级别的静态目录中使用名称间距。

app1应用程序1

app1/static/app1/files

app2应用程序2

app2/static/app2/files 

static file namespacing静态文件命名空间

Now we might be able to get away with putting our static files directly in my_app/static/ (rather than creating another my_app subdirectory), but it would actually be a bad idea.现在我们可以将静态文件直接放在 my_app/static/ 中(而不是创建另一个 my_app 子目录),但这实际上是一个坏主意。 Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would be unable to distinguish between them. Django 将使用它找到的第一个名称匹配的静态文件,如果您在不同的应用程序中有一个同名的静态文件,Django 将无法区分它们。 We need to be able to point Django at the right one, and the best way to ensure this is by namespacing them.我们需要能够将 Django 指向正确的位置,而确保这一点的最佳方法是对它们进行命名空间。 That is, by putting those static files inside another directory named for the application itself.也就是说,通过将这些静态文件放在另一个以应用程序本身命名的目录中。

You can namespace static assets in STATICFILES_DIRS by specifying prefixes.您可以通过指定前缀来命名 STATICFILES_DIRS 中的静态资产。

The way you use declare the static file is not right, in your example:您使用声明 static 文件的方式不正确,在您的示例中:

  <link rel="stylesheet" href="{% static "style/fesahat.css" %}" />

You are closing the double quotes when declaring the path to your css files, You should combine double and single quotes like this:您在声明 css 文件的路径时关闭双引号,您应该像这样组合双引号和单引号:

  <link rel="stylesheet" href="{% static 'style/fesahat.css' %}" />

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

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