2975cca168c44f8a450748e2c30e9321717966ce
[myslice.git] / engine / prelude.py
1 from types import StringTypes, ListType
2
3 from django.template.loader import render_to_string
4
5 class Prelude:
6
7     """A class for collecting dependencies on js/css files or fragments"""
8
9     keys=[ 'js_files','css_files','js_chunks', 'css_chunks' ]
10     def __init__ (self, js_files=[], css_files=[], js_chunks=[], css_chunks=[]):
11         # it's tempting to use sets but sets are not ordered..
12         self.js_files  = Prelude._normalize(js_files)
13         self.css_files = Prelude._normalize(css_files)
14         self.js_chunks = Prelude._normalize(js_chunks)
15         self.css_chunks= Prelude._normalize(css_chunks)
16
17     @staticmethod
18     def _normalize (input):
19         if   isinstance (input, ListType):      return input
20         elif isinstance (input, StringTypes):   return [ input ]
21         else:                                   return list (input)
22
23     def add_js_files (self, x):
24         for i in Prelude._normalize (x):
25             if i not in self.js_files: self.js_files.append(i)
26     def add_css_files (self, x):
27         for i in Prelude._normalize (x):
28             if i not in self.css_files: self.css_files.append(i)
29     def add_js_chunks (self, x):
30         self.js_chunks += Prelude._normalize (x)
31     def add_css_chunks (self, x):
32         self.css_chunks += Prelude._normalize (x)
33
34     # first attempt was to use a simple dict like this
35     #    env={}
36     #    env['js_files']=  self.js_files
37     #    env['css_files']= self.css_files
38     #    env['js_chunks']= '\n'.join(self.js_chunks)
39     #    env['css_chunks']='\n'.join(self.css_chunks)
40     #    return env
41     # together with this in layout-myslice.html
42     # {% for js_file in js_files %} {% insert_str prelude js_file %} {% endfor %}
43     # {% for css_file in css_files %} {% insert_str prelude css_file %} {% endfor %}
44     # somehow however this would not work too well, 
45     # probably insert_above is not powerful enough to handle that
46     # 
47     # so a much simpler and safer approach is for use to compute the html header directly
48     def template_env (self): 
49         env={}
50         env['js_files']=  self.js_files
51         env['css_files']= self.css_files
52         env['js_chunks']= self.js_chunks
53         env['css_chunks']=self.css_chunks
54         # not sure how this should be done more cleanly
55         from myslice.settings import STATIC_URL
56         env ['STATIC_URL'] = STATIC_URL
57         # render this with prelude.html and put the result in header_prelude
58         header_prelude = render_to_string ('header-prelude.html',env)
59         return { 'header_prelude' : header_prelude }