diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 6686cf973..c577040c6 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -12,6 +12,7 @@ Changelog * Added a new datetime picker widget * Added styleguide (mainly for wagtail developers) * Aesthetic improvements to preview experience + * Added an 'attrs' property to image rendition objects to output src, width, height and alt attributes all in one go * Fix: Animated GIFs are now coalesced before resizing * Fix: Wand backend clones images before modifying them * Fix: Admin breadcrumb now positioned correctly on mobile diff --git a/docs/building_your_site/frontenddevelopers.rst b/docs/building_your_site/frontenddevelopers.rst index f0054eaab..a8cf6a25e 100644 --- a/docs/building_your_site/frontenddevelopers.rst +++ b/docs/building_your_site/frontenddevelopers.rst @@ -197,6 +197,11 @@ In some cases greater control over the ``img`` tag is required, for example to a {{ tmp_photo.alt }} +You can also use the ``attrs`` property as a shorthand to output the ``src``, ``width``, ``height`` and ``alt`` attributes in one go: + +.. code-block:: django + + .. _rich-text-filter: diff --git a/wagtail/wagtailimages/models.py b/wagtail/wagtailimages/models.py index 8137971a7..8535199e7 100644 --- a/wagtail/wagtailimages/models.py +++ b/wagtail/wagtailimages/models.py @@ -236,11 +236,15 @@ class AbstractRendition(models.Model): def url(self): return self.file.url - def img_tag(self): + @property + def attrs(self): return mark_safe( - '%s' % (escape(self.url), self.width, self.height, escape(self.image.title)) + 'src="%s" width="%d" height="%d" alt="%s"' % (escape(self.url), self.width, self.height, escape(self.image.title)) ) + def img_tag(self): + return mark_safe('' % self.attrs) + class Meta: abstract = True diff --git a/wagtail/wagtailimages/tests.py b/wagtail/wagtailimages/tests.py index 4604a94ef..d546c396d 100644 --- a/wagtail/wagtailimages/tests.py +++ b/wagtail/wagtailimages/tests.py @@ -197,6 +197,18 @@ class TestImageTag(TestCase): self.assertTrue('height="300"' in result) self.assertTrue('alt="Test image"' in result) + def render_image_tag_as(self, image, filter_spec): + temp = template.Template('{% load image_tags %}{% image image_obj ' + filter_spec + ' as test_img %}') + context = template.Context({'image_obj': image}) + return temp.render(context) + + def test_image_tag_attrs(self): + result = self.render_image_tag_as(self.image, 'width-400') + + # Check that all the required HTML attributes are set + self.assertTrue('width="400"' in result) + self.assertTrue('height="300"' in result) + self.assertTrue('alt="Test image"' in result) ## ===== ADMIN VIEWS =====