静态文件
静态文件
介绍
Masonite 试图使静态文件变得非常容易,自带 whitenoise 包开箱即用。 Whitenoise 包装 WSGI 应用程序并侦听某些可以在您的配置文件中拒绝的 URI 请求。
配置
所有特定于静态资源的配置都可以在 config/storage.py
文件找到。在这个文件里,您可以看到一个常量叫做 STATICFILES
,它就是一个目录的字典,目录作为键,别名作为值。
作为键包含进来的目录就是您静态资源的位置。例如,您的 css 文件在 storage/assets/css
中,将该目录位置作为键。对于值,就是您将要在模板中使用的别名。如下,我们将使用 assets /
作为别名。
对于此设置,我们的 STATICFILES
常量应类似于:
config/storage.py
STATICFILES = {
'storage/assets/css': 'assets/',
}
现在,我们可以在模板中使用:
<img src="/assets/style.css">
我们将会得到 storage/assets/css/style.css
文件。
Static 模板方法
所有的模板都具有一个 static 方法,可以帮助获取到静态文件的位置。您可以使用驱动程序名称或点表示法指定驱动程序和所需的位置。
例如:
config/storage.py
....
's3': {
's3_client': 'sIS8shn...'
...
'location': 'https://s3.us-east-2.amazonaws.com/bucket'
},
....
...
<img src="{{ static('s3', 'profile.jpg') }}" alt="profile">
...
将渲染:
<img src="https://s3.us-east-2.amazonaws.com/bucket/profile.jpg" alt="profile">
You can also make the config location a dictionary and use dot notation:
您还可以将配置的 location 设置为字典并使用点符号:
config/storage.py
....
's3': {
's3_client': 'sIS8shn...'
...
'location': {
'east': 'https://s3.us-east-2.amazonaws.com/east-bucket',
'west': 'https://s3.us-west-16.amazonaws.com/west-bucket'
},
....
并像这样使用点符号:
...
<img src="{{ static('s3.east', 'profile.jpg') }}" alt="profile">
...
<img src="{{ static('s3.west', 'profile.jpg') }}" alt="profile">
...
提供 "Root" 文件
通常您需要在程序的根目录提供一些类似于 robots.txt
或 manifest.json
的文件。这些文件可以使用 config/storage.py
文件中 的 STATICFILES
常量指定别名。它们不必位于项目的根目录中,而可以位于 storage / root
或 storage / public
目录中,并以简单的/
作为别名。
例如,一个基本目录结构如下:
resources/
routes/
storage/
static/
root/
robots.txt
manifest.json
您可以在 STATICFILES
常量中对此进行别名:
config/storage.py
STATICFILES = {
# folder # template alias
'storage/static': 'static/',
...
'storage/root': '/'
}
现在,您将可以访问 localhost:8000 / robots.txt
,并且可以正确提供 robots.txt ,搜索引擎可以正确地对其进行索引。
静态资源这块就这些内容,简单吧。
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。