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 print 'add_js_chunks BEFORE',len(self.js_chunks)
34 self.js_chunks += Prelude._normalize (x)
35 print 'add_js_chunks AFTER',len(self.js_chunks)
36 def add_css_chunks (self, x):
37 self.css_chunks += Prelude._normalize (x)
39 def inspect_string (self,msg):
40 result = 'Prelude.inspect %s (%s) with '%(msg,self)
41 result += ",".join( [ "%s->%s"%(k,len(getattr(self,k))) for k in ['js_files','js_chunks','css_files','css_chunks'] ] )
43 def inspect (self,msg):
44 print self.inspect_string(msg)
46 # first attempt was to use a simple dict like this
48 # env['js_files']= self.js_files
49 # env['css_files']= self.css_files
50 # env['js_chunks']= '\n'.join(self.js_chunks)
51 # env['css_chunks']='\n'.join(self.css_chunks)
53 # together with this in layout-myslice.html
54 # {% for js_file in js_files %} {% insert_str prelude js_file %} {% endfor %}
55 # {% for css_file in css_files %} {% insert_str prelude css_file %} {% endfor %}
56 # somehow however this would not work too well,
57 # probably insert_above is not powerful enough to handle that
59 # so a much simpler and safer approach is for use to compute the html header directly
60 def template_env (self):
61 inspect = self.inspect ('template_env')
64 env['js_files']= self.js_files
65 env['css_files']= self.css_files
66 env['js_chunks']= self.js_chunks
67 env['css_chunks']=self.css_chunks
68 # not sure how this should be done more cleanly
69 from myslice.settings import STATIC_URL
70 env ['STATIC_URL'] = STATIC_URL
71 # render this with prelude.html and put the result in header_prelude
72 header_prelude = render_to_string ('header-prelude.html',env)
73 return { 'header_prelude' : header_prelude }