2020-01-21 06:35:58 +00:00
|
|
|
from textwrap import dedent
|
|
|
|
|
|
|
|
from django import forms
|
|
|
|
from django.conf import settings
|
|
|
|
from django.template import Context, Template
|
|
|
|
from lxml import html
|
|
|
|
|
|
|
|
|
|
|
|
class CompressorWidgetMixin(object):
|
2022-05-14 17:57:27 +00:00
|
|
|
__template_css = dedent(
|
|
|
|
"""\
|
2020-01-21 06:35:58 +00:00
|
|
|
{% compress css %}
|
|
|
|
{{ media.css }}
|
|
|
|
{% endcompress %}
|
2022-05-14 17:57:27 +00:00
|
|
|
"""
|
|
|
|
)
|
2020-01-21 06:35:58 +00:00
|
|
|
|
2022-05-14 17:57:27 +00:00
|
|
|
__template_js = dedent(
|
|
|
|
"""\
|
2020-01-21 06:35:58 +00:00
|
|
|
{% compress js %}
|
|
|
|
{{ media.js }}
|
|
|
|
{% endcompress %}
|
2022-05-14 17:57:27 +00:00
|
|
|
"""
|
|
|
|
)
|
2020-01-21 06:35:58 +00:00
|
|
|
|
|
|
|
__templates = {
|
2022-05-14 17:57:27 +00:00
|
|
|
(False, False): Template(""),
|
|
|
|
(True, False): Template("{% load compress %}" + __template_css),
|
|
|
|
(False, True): Template("{% load compress %}" + __template_js),
|
|
|
|
(True, True): Template("{% load compress %}" + __template_js + __template_css),
|
2020-01-21 06:35:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
compress_css = False
|
|
|
|
compress_js = False
|
|
|
|
|
|
|
|
try:
|
|
|
|
import compressor
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
else:
|
2022-05-14 17:57:27 +00:00
|
|
|
if getattr(settings, "COMPRESS_ENABLED", not settings.DEBUG):
|
|
|
|
|
2020-01-21 06:35:58 +00:00
|
|
|
@property
|
|
|
|
def media(self):
|
|
|
|
media = super().media
|
|
|
|
template = self.__templates[self.compress_css, self.compress_js]
|
2022-05-14 17:57:27 +00:00
|
|
|
result = html.fromstring(template.render(Context({"media": media})))
|
2020-01-21 06:35:58 +00:00
|
|
|
|
|
|
|
return forms.Media(
|
2022-05-14 17:57:27 +00:00
|
|
|
css={"all": [result.find(".//link").get("href")]}
|
|
|
|
if self.compress_css
|
|
|
|
else media._css,
|
|
|
|
js=[result.find(".//script").get("src")]
|
|
|
|
if self.compress_js
|
|
|
|
else media._js,
|
2020-01-21 06:35:58 +00:00
|
|
|
)
|