Search code examples
thymeleaf

Thymeleaf, how to make conditional statement with th:src?


If dish.imageFolder is not null - it should be

<img th:src="@{${dish.imageFolder}}"/>

If null - this image

  <img src="https://via.placeholder.com/150" alt=""/>

Solution

  • One option:

    <img th:src="${dish.imageFolder != null} ? @{${dish.imageFolder}} : 'https://via.placeholder.com/150'" />
    

    I would probably just use th:if though, like this:

      <img th:if="${dish.imageFolder != null}" th:src="@{${dish.imageFolder}}" />
      <img th:if="${dish.imageFolder == null}" src="https://via.placeholder.com/150" />