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