css.py 2.43 KB
Newer Older
1
from compressor.base import Compressor, SOURCE_HUNK, SOURCE_FILE
2
from compressor.conf import settings
3

4

5 6
class CssCompressor(Compressor):

7
    def __init__(self, content=None, output_prefix="css", context=None):
8 9
        filters = list(settings.COMPRESS_CSS_FILTERS)
        super(CssCompressor, self).__init__(content, output_prefix, context, filters)
10 11 12 13 14 15 16 17 18

    def split_contents(self):
        if self.split_content:
            return self.split_content
        self.media_nodes = []
        for elem in self.parser.css_elems():
            data = None
            elem_name = self.parser.elem_name(elem)
            elem_attribs = self.parser.elem_attribs(elem)
19
            if elem_name == 'link' and 'rel' in elem_attribs and elem_attribs['rel'].lower() == 'stylesheet':
20 21 22
                basename = self.get_basename(elem_attribs['href'])
                filename = self.get_filename(basename)
                data = (SOURCE_FILE, filename, basename, elem)
23
            elif elem_name == 'style':
24
                data = (SOURCE_HUNK, self.parser.elem_content(elem), None, elem)
25 26 27
            if data:
                self.split_content.append(data)
                media = elem_attribs.get('media', None)
28 29 30 31
                # Append to the previous node if it had the same media type
                append_to_previous = self.media_nodes and self.media_nodes[-1][0] == media
                # and we are not just precompiling, otherwise create a new node.
                if append_to_previous and settings.COMPRESS_ENABLED:
32 33
                    self.media_nodes[-1][1].split_content.append(data)
                else:
34
                    node = self.__class__(content=self.parser.elem_str(elem),
35
                                          context=self.context)
36 37 38 39
                    node.split_content.append(data)
                    self.media_nodes.append((media, node))
        return self.split_content

40
    def output(self, *args, **kwargs):
41 42
        if (settings.COMPRESS_ENABLED or settings.COMPRESS_PRECOMPILERS or
                kwargs.get('forced', False)):
43
            # Populate self.split_content
44 45 46 47 48 49 50 51
            self.split_contents()
            if hasattr(self, 'media_nodes'):
                ret = []
                for media, subnode in self.media_nodes:
                    subnode.extra_context.update({'media': media})
                    ret.append(subnode.output(*args, **kwargs))
                return ''.join(ret)
        return super(CssCompressor, self).output(*args, **kwargs)