wagtail / wagtail

A Django content management system focused on flexibility and user experience

Home Page:https://wagtail.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Need additional attributes for picture tag

andre-fuchs opened this issue · comments

I love the picture template tag, which renders a picture element with multiple image format sources. This works perfectly fine and simplifies my template code for images significantly. The only feature missing here are additional attributes like a class name or a custom alt attribute, for example. For now the picture tag renders the img element with the file name as alt text, which is not satisfying. Or is this already possible but not documented yet?

Hello (again) @andre-fuchs

Wagtail uses the default_alt_text property on the Image model to determine what alt text to render: permalink to relevant source.
By default, this returns the image title field. This title field is pre-filled with the filename of the image you uploaded. This behaviour is documented in the accessibility considerations (link to docs)

The docs acknowledge using filenames as alt text by default is not really appropriate as it is not clearly communicated in the interface.

The good news is that there are improvements on the horizon in the form of a Google Summer of Code project. If you are interested, here is a link to the discussion.


To summarise;

  1. if you want to change the default alt text for an image you should override the default_alt_text property implementation in a custom Image model.

  2. if you want to explicitly override the alt text for a <picture> rendered using {% picture %}, you can explicitly pass an alt attribute. You might want to do this if you have contextually aware alt text. Here's an example:

{% picture page.promo_image format-{avif,webp,jpeg} fill-590x413-c100 alt=page.promo_image_alt_text %}

Note: I couldn't find any mention of being able to override the alt text like this in the docs for the picture templatetag – I suppose it would make a good docs addition.

Thanks, @Stormheg. It would make sense to allow custom attributes in this picture tag, like "class", "data", "zoom", too. To my limited knowledge of Django template tags this is not possible, right?

And, yes, I used custom Image model before as a workaround. Good to know that the picture tag allows custom alt tag values.

I'm not sure, just tried it on bakerydemo with Wagtail 6.0 and it appears to be possible to add extra attributes.

{% picture page.promo_image format-{avif,webp,jpeg} fill-590x413-c100 alt="custom alt" class="custom-class" data-test-id="my_img" %}

# renders as:
<picture>
    # <source> elements omitted for brevity...
    <img alt="custom alt" class="custom-class" data-test-id="my_img" height="413" src="..." width="590">
</picture>