[3563] | 1 | """ This module dedicated to work with viewlets. """ |
---|
| 2 | from Acquisition import aq_inner |
---|
| 3 | |
---|
| 4 | from plone.app.customerize import registration |
---|
| 5 | |
---|
| 6 | from zope.publisher.interfaces.browser import IBrowserRequest |
---|
| 7 | from zope.viewlet.interfaces import IViewlet |
---|
| 8 | |
---|
| 9 | |
---|
[3608] | 10 | # TODO: Methods 'getViewletByName' and 'setupViewletByName' were copied from |
---|
| 11 | # https://github.com/collective/collective.developermanual/blob/master/source/ |
---|
| 12 | # views/viewlets.rst#rendering-viewlet-by-name |
---|
[3598] | 13 | # Better solution would be to use collective.fastview |
---|
| 14 | # (http://svn.plone.org/svn/collective/collective.fastview/trunk/) |
---|
[3563] | 15 | # which has not yet included in plone. |
---|
| 16 | |
---|
| 17 | def getViewletByName(name): |
---|
| 18 | """ Viewlets allow through-the-web customizations. |
---|
| 19 | |
---|
| 20 | Through-the-web customization magic is managed by five.customerize. |
---|
| 21 | We need to think of this when looking up viewlets. |
---|
| 22 | |
---|
| 23 | @return: Viewlet registration object |
---|
| 24 | """ |
---|
| 25 | views = registration.getViews(IBrowserRequest) |
---|
| 26 | |
---|
| 27 | for v in views: |
---|
| 28 | |
---|
| 29 | if v.provided == IViewlet: |
---|
[3608] | 30 | # Note that we might have conflicting BrowserView with the |
---|
| 31 | # same name, thus we need to check for provided |
---|
[3563] | 32 | if v.name == name: |
---|
| 33 | return v |
---|
| 34 | |
---|
| 35 | return None |
---|
| 36 | |
---|
| 37 | |
---|
| 38 | def setupViewletByName(view, context, request, name): |
---|
| 39 | """ Constructs a viewlet instance by its name. |
---|
| 40 | |
---|
| 41 | Viewlet update() and render() method are not called. |
---|
| 42 | |
---|
| 43 | @return: Viewlet instance of None if viewlet with name does not exist |
---|
| 44 | """ |
---|
| 45 | context = aq_inner(context) |
---|
| 46 | |
---|
| 47 | # Perform viewlet regisration look-up |
---|
| 48 | # from adapters registry |
---|
| 49 | reg = getViewletByName(name) |
---|
[3598] | 50 | if reg is None: |
---|
[3563] | 51 | return None |
---|
| 52 | |
---|
| 53 | # factory method is responsible for creating the viewlet instance |
---|
| 54 | factory = reg.factory |
---|
| 55 | |
---|
| 56 | # Create viewlet and put it to the acquisition chain |
---|
| 57 | # Viewlet need initialization parameters: context, request, view |
---|
| 58 | try: |
---|
| 59 | viewlet = factory(context, request, view, None).__of__(context) |
---|
| 60 | except TypeError: |
---|
| 61 | # Bad constructor call parameters |
---|
[3608] | 62 | raise RuntimeError("Unable to initialize viewlet %s. Factory " |
---|
| 63 | "method %s call failed." % (name, str(factory))) |
---|
[3563] | 64 | |
---|
| 65 | return viewlet |
---|