pass python settings to the js layer - from plugin.php
[unfold.git] / engine / plugin.py
1 # this is the abstract interface for Plugin instances
2 # so it should be specialized in real plugin classes
3 # like e.g. plugins.simplelist.SimpleList
4
5 import json
6
7 from django.template.loader import render_to_string
8
9 class Plugin:
10
11     uid=0
12
13     def __init__ (self, **settings):
14         self.uuid=Plugin.uid
15         Plugin.uid += 1
16         # we store as a dictionary the arguments passed to constructor
17         # e.g. SimpleList (visible=True) => _settings = {'visible':True}
18         self._settings=settings
19
20     def get_class (self): return type(self).__name__
21
22     # shorthands to inspect _settings
23     def get_setting (self, setting, default):
24         if setting not in self._settings: return default
25         else:                             return self._settings[setting]
26
27     def is_visible (self): return self.get_setting ('visible',True)
28     def is_hidable (self): return self.get_setting ('hidable',False)
29     def is_hidden_by_default (self): return self.get_setting ('hidden_by_default', False)
30
31     # returns the html code for that plugin
32     # in essence, wraps the results of self.render_content ()
33     def render (self, request):
34         uuid = self.uuid
35         title = self.get_class()
36         plugin_content = self.render_content (request)
37
38         # expose _settings in json format to js
39         settings_json = json.dumps(self._settings, separators=(',',':'))
40
41         # xxx missing from the php version
42         # compute an 'optionstr' from the set of available settings/options as a json string
43         # that gets passed to jquery somehow
44         # see the bottom of 
45         result = render_to_string ('widget-plugin.html',
46                                    {'uuid':uuid, 'title':title,
47                                     'visible':self.is_visible(),
48                                     'hidable':self.is_hidable(),
49                                     'hidden':self.is_hidden_by_default(),
50                                     'plugin_content' : plugin_content,
51                                     'settings' : settings_json,
52                                     })
53
54         return result
55         
56     ### abstract interface
57     # you may redefine this completely, but if you don't we'll just use method 
58     # template() to find out which template to use, and env() to find out which 
59     # dictionary to pass the templating system
60     def render_content (self, request):
61         """Should return an HTML fragment"""
62         template = self.template()
63         env=self.env()
64         return render_to_string (template, env)