Get view name from within a viewlet

Hi,

I've been hitting this problem now and then, and never found a decent solution for it.

I have a viewlet that I want to customize for a specific view, of the several where the viewlet is shown on.

My first approach is to try to find the name of the view (as configured in ZCML).

So that given something like:

  <browser:viewlet
    name="plone.htmlhead.title"
    for="*"
    manager="plone.app.layout.viewlets.interfaces.IHtmlHead"
    class="my.addon.viewlets.title.MyTitleViewlet"
    permission="zope2.View"
    />

And on TitleViewlet have something like:

from plone.app.layout.viewlets.common import TitleViewlet

class MyTitleViewlet(TitleViewlet):
    def update(self):
        if self.XXX == 'my-view':
            self.site_title = 'a custom title'
        elif self.YYY == 'another-view'
            self.site_title = 'another title'
        else:
            self.site_title = 'fallback value'

Would be great if one could do that from within the template as well:

<metal:head_slot fill-slot="head_slot">
  <title>Blue New Deal</title>
</metal:head_slot>

But given that on main_template.pt we have:

    <div tal:replace="structure provider:plone.htmlhead" />

The viewlets take precedence I guess :thinking:

I see that the template changes do actually work, but they do not replace the viewlet provided title, but append it, so as it is the second <title> browsers ignore it and pick the first one.

the <browser:viewlet /> directive has the view property. You could register viewlets for different views then. See https://github.com/zopefoundation/zope.viewlet/blob/master/src/zope/viewlet/metaconfigure.py#L33

The default viewlet class saves the current view in self.__parent__ (https://github.com/zopefoundation/zope.viewlet/blob/master/src/zope/viewlet/viewlet.py#L37) ... maybe helpful too ...

1 Like

Thanks! I will have a look and report back! :sparkles: