1 from types import StringTypes, ListType
3 from django.template.loader import render_to_string
9 """A class for collecting dependencies on js/css files or fragments"""
11 keys=[ 'js_files','css_files','js_chunks', 'css_chunks' ]
12 def __init__ (self, js_files=None, css_files=None, js_chunks=None, css_chunks=None):
13 # it's tempting to use sets but sets are not ordered..
14 self.js_files = Prelude._normalize(js_files)
15 self.css_files = Prelude._normalize(css_files)
16 self.js_chunks = Prelude._normalize(js_chunks)
17 self.css_chunks= Prelude._normalize(css_chunks)
20 def _normalize (input):
21 if not input: return []
22 elif isinstance (input, ListType): return input
23 elif isinstance (input, StringTypes): return [ input ]
24 else: return list (input)
26 def add_js_files (self, x):
27 for i in Prelude._normalize (x):
28 if i not in self.js_files: self.js_files.append(i)
29 def add_css_files (self, x):
30 for i in Prelude._normalize (x):
31 if i not in self.css_files: self.css_files.append(i)
32 def add_js_chunks (self, x):
33 self.js_chunks += Prelude._normalize (x)
34 def add_css_chunks (self, x):
35 self.css_chunks += Prelude._normalize (x)
37 def inspect_string (self,msg):
38 result = 'Prelude.inspect %s (%s) with '%(msg,self)
39 result += ",".join( [ "%s->%s"%(k,len(getattr(self,k))) for k in ['js_files','js_chunks','css_files','css_chunks'] ] )
41 def inspect (self,msg):
42 print self.inspect_string(msg)
44 # first attempt was to use a simple dict like this
46 # env['js_files']= self.js_files
47 # env['css_files']= self.css_files
48 # env['js_chunks']= '\n'.join(self.js_chunks)
49 # env['css_chunks']='\n'.join(self.css_chunks)
51 # together with this in layout-unfold1.html
52 # {% for js_file in js_files %} {% insert_str prelude js_file %} {% endfor %}
53 # {% for css_file in css_files %} {% insert_str prelude css_file %} {% endfor %}
54 # somehow however this would not work too well,
55 # probably insert_above is not powerful enough to handle that
57 # so a much simpler and safer approach is for use to compute the html header directly
58 def prelude_env (self):
60 env['js_files']= self.js_files
61 env['css_files']= self.css_files
62 env['js_chunks']= self.js_chunks
63 env['css_chunks']=self.css_chunks
65 print "prelude has %d js_files, %d css files, %d js chunks and %d css_chunks"%\
66 (len(self.js_files),len(self.css_files),len(self.js_chunks),len(self.css_chunks),)
67 # not sure how this should be done more cleanly
68 from myslice.settings import STATIC_URL
69 env ['STATIC_URL'] = STATIC_URL
70 # render this with prelude.html and put the result in header_prelude
71 header_prelude = render_to_string ('prelude.html',env)
72 return { 'header_prelude' : header_prelude }