Django 的css和js压缩插件:django_compressor
作者:Wally Yu
今天尝试了django_conpressor,一个在django框架中压缩css和js的插件,灰常有用
我把它加载在我的base的HTML template中,原来未经压缩的css和js是:
<link rel="stylesheet" href = "include/style.css" type="text/css">
<link rel="stylesheet" href = "include/demo_page.css" type="text/css">
<link rel="stylesheet" href = "include/demo_table.css" type="text/css">
<script type="text/javascript" src="include/CloudTesting.js"></script>
<script src='include/jquery.min.js' type='text/javascript'></script>
<script type='text/javascript' src='include/jquery.dataTables.js'></script>
<link rel="stylesheet" href="include/CACHE/css/31b7bf7183d6.css" type="text/css" />
<script type="text/javascript" src="include/CACHE/js/3b54f0a1ee64.js"></script>
详细的参见官方说明:http://django_compressor.readthedocs.org/en/latest/quickstart/
自己整理的关键步骤:
1. 安装:
pip install django_compressor2. 添加到setting.py中:
INSTALLED_APPS = ( # other apps "compressor", )
STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. 'compressor.finders.CompressorFinder', )3. 在settings.朋友中加入一些必要的配置:
COMPRESS_ROOT = 'Templates/include/'
COMPRESS_URL = 'include/'
COMPRESS_ENABLED = True
4. 使用起来很方便:
{% load compress %}
{% compress css %}
<link rel="stylesheet" href = "include/style.css" type="text/css">
<link rel="stylesheet" href = "include/demo_page.css" type="text/css">
<link rel="stylesheet" href = "include/demo_table.css" type="text/css">
{% endcompress %}
{% compress js %}
<script type="text/javascript" src="include/CloudTesting.js"></script>
<script src='include/jquery.min.js' type='text/javascript'></script>
<script type='text/javascript' src='include/jquery.dataTables.js'></script>
{% endcompress %}
注意:
COMPRESS_URL一定要以“/”结尾,否则会报“django.core.exceptions.ImproperlyConfigured: URL settings (e.g. COMPRESS_URL) mu
st have a trailing slash”这样的错