Display vocabulary term title for fields value in custom view

I always stumble over this: I have a custom view and want to display a field with vocabulary.

So, I copy code around - from project to project - into my view class like so:

from plone.dexterity.utils import iterSchemata
...
    def get_term_title_for(self, fieldname, context=None, default="-/-"):
        __traceback_info__ = fieldname
        if context is None:
            context = self.context
        field = [s.get(fieldname) for s in iterSchemata(context) if fieldname in s.names()][0]
        # next not perfect, todo: behavior adaption needed
        value = getattr(context, fieldname, _marker)
        if value is _marker:
            value = field.default
        try: 
            return field.vocabulary.by_value[value].title
        except KeyError:
            return default

Question: Is anyone aware of something like this in Plone Core itself?

If not: is this a candidate for plone.api?

Like

  • plone.api.content.get_field(name, context) -> returns field
  • plone.api.content.term_by_field(name, context) -> returns term (what would be a better name for the function?)
2 Likes

Doesn't the DX display view handle that?
view/w/my_field/render or something like that