2

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 ?

Raphaël Lemaire
  • 1,269
  • 1
  • 13
  • 23
  • 1
    How about the Elvis operator and single quotes for the default value? `` . Many ways to do it, adding an empty check if you need it. https://stackoverflow.com/questions/20636456/using-thymeleaf-when-the-value-is-null – riddle_me_this Oct 10 '19 at 17:22
  • 1
    The result is the same with an empty string : the attribute is removed. – Raphaël Lemaire Oct 11 '19 at 08:38
  • Interesting - may have been a design choice to remove the attribute altogether. Similar discussion in this question: https://stackoverflow.com/questions/42935823/creating-empty-data-attributes-in-thymeleaf/42936361 – riddle_me_this Oct 11 '19 at 13:14

1 Answers1

2

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.)

Metroids
  • 18,999
  • 4
  • 41
  • 52
  • Agreed, I think this attribute should be changed to work differently at the Thymeleaf level. I just don't think there is an elegant solution for this... – Metroids Oct 14 '19 at 18:48