Thymeleaf conditional img src

12,047

Solution 1

try

<img th:src="${(comment.user.image != null && !#strings.isEmpty(comment.user.image)) ? comment.user.image : '/images/default-user.png'}" th:alt="${comment.user.nameSurname}"/>

Solution 2

try.. change && to AND

<img th:src="${(comment.user.image != null && !#strings.isEmpty(comment.user.image)) ? comment.user.image : '/images/default-user.png'}" th:alt="${comment.user.nameSurname}"/>

to

<img th:src="${(comment.user.image != null AND !#strings.isEmpty(comment.user.image)) ? comment.user.image : '/images/default-user.png'}" th:alt="${comment.user.nameSurname}"/>
Share:
12,047
moonwalker
Author by

moonwalker

Updated on June 11, 2022

Comments

  • moonwalker
    moonwalker almost 2 years

    I want to show the user avatar if it exists and show a default avatar if not. The code I use is:

    <img src="/images/commentavatar1.png" th:src="${comment.user.image} != null ? ${comment.user.image} : '/images/default-user.png'" th:alt="${comment.user.nameSurname}"/>
    

    What I see is only the alt tag. The rendered element has an empty src attribute. Thank you.

  • moonwalker
    moonwalker over 8 years
    Thank you very much. This effectively checks whether string is empty or not which was exactly the case with our back-end. Большое спасибо, удачи.
  • rineez
    rineez over 2 years
    I'm wondering why is @{...} syntax not used for link in this answer? Is @{...} syntax added only recently? Or does it not work with such conditional expressions?