16e28f30071ada65fa8afe92c606ebf319f3342c
[myslice.git] / unfold / composite.py
1 from unfold.plugin import Plugin
2
3 # this is a simple base class for plugins that contain/arrange a set of other plugins
4 # sons is expected to be a list of the contained plugins, and 
5 # active_domid is the domid for the one son that should be displayed as active
6 # some subclasses of Composite, like e.g. Tabs, will not behave as expected 
7 # if a valid active_domid is not provided
8
9 class Composite (Plugin):
10
11     def __init__ (self, sons=None, active_domid=None, *args, **kwds):
12         Plugin.__init__ (self, *args, **kwds)
13         self.sons= sons if sons else []
14         self.active_domid=active_domid
15         # make sure this is valid, unset otherwise, so we always have exactly one active
16         self.check_active_domid()
17         
18     def check_active_domid(self):
19         matches= [ son for son in self.sons if son.domid==self.active_domid ]
20         if len(matches)!=1: 
21             print "WARNING: %s has %d valid son(s) for being active - expecting 1, resetting"%\
22                 (self,len(matches))
23             self.active_domid=None
24         
25     def insert (self, plugin):
26         self.sons.append(plugin)
27
28     def template_env (self, request):
29         # this is designed so as to support a template like
30         # {% for son in sons %} {{ son.rendered }} ...
31         def is_active (son,rank):
32             # if active_domid is not specified, make the first one active
33             if not self.active_domid: return rank==0
34             return son.domid==self.active_domid
35         ranks=range(len(self.sons))
36         env = { 'sons':
37                  [ { 'rendered': son.render(request),
38                      'rank': rank,
39                      'is_active': is_active(son,rank),
40                      'title': son.title,
41                      'domid': son.domid,
42                      'classname': son.classname,
43                      }
44                    for (son,rank) in zip(self.sons,ranks) ]}
45         return env
46