diff --git a/news/128.bugfix b/news/128.bugfix new file mode 100644 index 00000000..ef954278 --- /dev/null +++ b/news/128.bugfix @@ -0,0 +1,4 @@ +Get title from ImageScale class. +Prevents a traceback when the context is a tile. +When no title can we found, fall back to an empty string. +[maurits] diff --git a/plone/namedfile/scaling.py b/plone/namedfile/scaling.py index 1b75a27e..21efd53f 100644 --- a/plone/namedfile/scaling.py +++ b/plone/namedfile/scaling.py @@ -107,6 +107,24 @@ def srcset_attribute(self): srcset_attr = ", ".join(_srcset_attr) return srcset_attr + @property + def title(self): + """Get the title from the context. + + Let's not fail when we cannot find a title. + """ + try: + # Most Plone content items. + return self.context.Title() + except AttributeError: + pass + try: + # Can work on a tile and most other things. + return self.context.title + except AttributeError: + pass + return "" + def tag( self, height=_marker, @@ -123,9 +141,9 @@ def tag( width = getattr(self, "width", self.data._width) if alt is _marker: - alt = self.context.Title() + alt = self.title if title is _marker: - title = self.context.Title() + title = self.title values = [ ("src", self.url), diff --git a/plone/namedfile/tests/test_scaling.py b/plone/namedfile/tests/test_scaling.py index 1eabdc55..1aff2128 100644 --- a/plone/namedfile/tests/test_scaling.py +++ b/plone/namedfile/tests/test_scaling.py @@ -6,6 +6,7 @@ from plone.namedfile.file import NamedImage from plone.namedfile.interfaces import IAvailableSizes from plone.namedfile.interfaces import IImageScaleTraversable +from plone.namedfile.scaling import ImageScale from plone.namedfile.scaling import ImageScaling from plone.namedfile.testing import PLONE_NAMEDFILE_FUNCTIONAL_TESTING from plone.namedfile.testing import PLONE_NAMEDFILE_INTEGRATION_TESTING @@ -296,6 +297,13 @@ def get_info_by_hash(self, hash): return value +class TitleImageScale(ImageScale): + """ImageScale class with its own title property. + """ + + title = "title from class" + + # @patch.multiple( # "plone.namedfile.scaling.Img2PictureTag", # allowed_scales=patch_Img2PictureTag_allowed_scales, @@ -926,6 +934,28 @@ def test_height(self): self.assertEqual(scale_uid.data.info["uid"], "uid-0") self.assertIs(scale_uid.data, scale2.data) + def test_title(self): + # Test that a custom title property on an ImageScale class is used. + item = FakeImage("abcdef", "jpeg") + scaling = ImageScaling(item, None) + scaling._scale_view_class = TitleImageScale + self.assertEqual( + scaling.tag("image"), + 'title from class' + ) + self.assertEqual( + scaling.tag("image", alt="own alt"), + 'own alt' + ) + self.assertEqual( + scaling.tag("image", title="own title"), + 'title from class' + ) + self.assertEqual( + scaling.tag("image", alt="own alt", title="own title"), + 'own alt' + ) + def test_suite(): from unittest import defaultTestLoader