Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# Imports 

2 

3from django.conf import settings 

4from django.utils.safestring import mark_safe 

5from .base import Asset 

6 

7# Exports 

8 

9__all__ = ( 

10 "StyleElement", 

11 "StyleSheet", 

12) 

13 

14# Classes 

15 

16 

17class StyleElement(object): 

18 """A style to be included in a :py:class:`StyleSheet` collection. 

19 

20 This class is not used directly, but is added via the ``append()`` method of the collection. 

21 

22 """ 

23 

24 def __init__(self, identifier, content=None): 

25 """Initialize the style. 

26 

27 :param identifier: The unique identifier for the content. 

28 :type identifier: str 

29 

30 :param content: The content of the style. 

31 :type content: str 

32 

33 """ 

34 self.content = content or "<!-- empty style: %s -->" % identifier 

35 self.identifier = identifier 

36 

37 def __str__(self): 

38 return self.to_html() 

39 

40 def to_html(self): 

41 """Export the style as HTML; automatically calls ``mark_safe()``. 

42 

43 :rtype: str 

44 

45 """ 

46 a = list() 

47 a.append("<!-- %s -->" % self.identifier) 

48 a.append(self.content) 

49 return mark_safe("\n".join(a)) 

50 

51 

52class StyleSheet(Asset): 

53 """A collection of CSS styles.""" 

54 

55 def append(self, identifier, content=None, url=None, wrap=True): 

56 """Add CSS to the collection.""" 

57 if identifier in self._identifiers: 

58 raise ValueError("Duplicate style identifier: %s" % identifier) 

59 

60 if not content and not url: 

61 raise ValueError("Either content or url is required.") 

62 

63 if url is not None: 

64 if url.startswith("http") or url.startswith("/"): 

65 href = url 

66 else: 

67 href = "%s%s" % (settings.STATIC_URL, url) 

68 

69 _content = '<link rel="stylesheet" href="%s">' % href 

70 else: 

71 if wrap: 

72 _content = '<style>%s</style>' % content 

73 else: 

74 _content = content 

75 

76 style = StyleElement(identifier, content=_content) 

77 

78 self._identifiers.append(identifier) 

79 self._items.append(style) 

80 

81 return style