Accessibility : empty alt attribute in thymeleaf

Viewed 1093

It is a good practice to use an empty alt attribute for images that don't need or don't have a text description. This is done by setting an empty alt attribute :

<img alt=""...

However in thymealf, when using a dynamic alt text that resolves to something null or empty, the attribute is removed altogether :

<img th:alt="${media.altText}"...

Is there an elegant way to solve this issue ?

1 Answers

The only option here would probably be something like this:

<img th:if="${#strings.isEmpty(media.altText)}" alt="" ... />
<img th:unless="${#strings.isEmpty(media.altText)}" th:alt="${media.altText}" ... />

It does mean duplicating your image tags, which may or may not work for you but it should solve the empty alt tag problem. (You could probably add it to a fragment that you include which would solve the code duplication aspect at least.)

Related