0

So, I am trying to make a shop section and I cannot find a way to display an alt image in case my image doesn't exist.

Basically I use the Model to pass a List then with th:each I manage to make a card for each product. All images are called after the id of the product

Do you know what I am doing wrong?

<img th:if="(@{'static/products/' + ${product.id} + '.png') != null" th:src="@{'static/products/' + ${product.id} + '.png'}" class="card-img-top" alt="immagine_vinile">

doesn't seem to work being a @{} and not a ${}.

I apologize if my terms are not right but I am learning

2 Answers2

0

In your controller, add a property on your product that indicates if there is an image or not. If you are currently directly exposing your Product entity, then create a ProductDto where you can add that extra property. When you have done that, use it like this:

<img th:if="${product.hasImage}" 
     th:src="@{'static/products/' + ${product.id} + '.png'}" 
     class="card-img-top" alt="immagine_vinile">
Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211
0

Since I understand that you wish to display a placeholder image in the case that the initial image cannot be found (is null)

<img th:with="url=${(product.imageUrl) ?: 'path/to/your/placeholder/image.png')}"
                th:src="@{${url}}"
                alt="image"
              />

Where the product entity would contain a parameter (imageUrl) that holds the image source directory. Since the code you used to generate this path isn't complex, adding it to your entity would be quite simple.

The th:with parameter creates a local variable "url", that get's defined based on the value of the imageUrl field in your Product entity.

The code above would check if the model entity's field "imageUrl" is null (you don't need to manually check by declaring th:if="${product.imageUrl == null}" as Thymeleaf does this for you). The first image will only be displayed if the imageUrl field isn't null, else, the placeholder image's URL will be used instead.