'How to show an image conditionally in Thymeleaf?
I have a controller that returns a ReponseEntity<byte[]> image and I can show it with the following tag:
<img th:src="@{'./my-files/main-logo'}"
I can also show an image from the /img/ folder with this tag:
<img th:src="@{/img/default-logo.png}"
I want to show the image from the database when it is present, and the image from the folder as a default if the ResponseEntity is null.
I tried all kind of ternary conditions but none of them worked. Any suggestions?
Solution 1:[1]
Try using the attribute th:if="${...}" in your <img /> tag.
You can try to call the method which returns the image programatically (e.g. nameOfTheImageController.getImage(...)) and add a boolean to your model that represents whether the image is null or not.
Then, you can just add that boolean variable in the <img>'s th:if.
UPDATE
As mentioned in a comment in
HTML, Thymeleaf - displaying an image conditionally, you should wrap your <img> tag inside a <div> and put the th:if attribute in the <div> tag instead.
Solution 2:[2]
In my opinion, instead of changing the src of the image, you should change your /my-files/main-logo controller to return img/default-logo.png as a the ResponseEntity<byte[]> if there is no main-logo. That way you can just leave your image tag as is:
<img th:src="@{'./my-files/main-logo'}" />
If you don't want to do that, then yes, you'll have to add something to your controller that tells you whether or not you have a main logo. Something like this for example:
<img th:if="${has_logo}" th:src="@{'./my-files/main-logo'}" />
<img th:unless="${has_logo}" th:src="@{/img/default-logo.png}" />
Solution 3:[3]
Please use the following syntax. in your controller add a model attribute hasImageInDatabase when response is null. then from thymeleaf use the below syntax.
<img th:src="${(hasImageInDatabase ?: '/my-files/main-logo': '/img/default-logo.png'}"/>
Solution 4:[4]
This will work for you:
<img th:src="./my-files/main-logo" onerror="this.onerror=null;this.src='/img/default-logo.png';">
It means if the first link to the photo didn't work ("./my-files/main-logo" ) or was null, it will show the second photo('/img/default-logo.png').
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TwiN |
| Solution 2 | Metroids |
| Solution 3 | |
| Solution 4 |
