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 "JavaScript", 

11 "ScriptElement", 

12) 

13 

14# Classes 

15 

16 

17class JavaScript(Asset): 

18 """A collection of JavaScript content and URLs.""" 

19 

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

21 """Add JavaScript to the collection.""" 

22 if identifier in self._identifiers: 

23 raise ValueError("Duplicate javascript identifier: %s" % identifier) 

24 

25 if not content and not url: 

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

27 

28 if url is not None: 

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

30 src = url 

31 else: 

32 src = "%s%s" % (settings.STATIC_URL, url) 

33 

34 _content = '<script src="%s"></script>' % src 

35 else: 

36 if wrap: 

37 _content = '<script>%s</script>' % content 

38 else: 

39 _content = content 

40 

41 script = ScriptElement(identifier, content=_content) 

42 

43 self._identifiers.append(identifier) 

44 self._items.append(script) 

45 

46 return script 

47 

48 

49class ScriptElement(object): 

50 """A script to be included in a :py:class:`JavaScript` collection. 

51 

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

53 

54 """ 

55 

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

57 """Initialize the script. 

58 

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

60 :type identifier: str 

61 

62 :param content: The content of the script. 

63 :type content: str 

64 

65 """ 

66 self.content = content or "<!-- empty javascript: %s -->" % identifier 

67 self.identifier = identifier 

68 

69 def __str__(self): 

70 return self.to_html() 

71 

72 def to_html(self): 

73 """Export the script as HTML; automatically calls ``mark_safe()``. 

74 

75 :rtype: str 

76 

77 """ 

78 a = list() 

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

80 a.append(self.content) 

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

82