Home > Mobile >  Can not realize thymleaf logic with image
Can not realize thymleaf logic with image

Time:04-16

I have following expression:

<img th:src="@{/api/file/{imageName}(imageName = ${account.profileImageLink})}" alt="profile picture"> 

and I want to realize next logic: if imageName equals null so imageName = "profile.jpg"

how can I do that through Thymleaf?

CodePudding user response:

Lots of different ways to accomplish this.

  1. The elvis operator:

    <img th:src="@{/api/file/{imageName}(imageName=${account.profileImageLink} ?: 'profile.jpg')}" alt="profile picture">
    
  2. Conditionals.

    <img th:if="${account.profileImageLink != null}" th:src="@{/api/file/{imageName}(imageName = ${account.profileImageLink})}" alt="profile picture">
    <img th:unless="${account.profileImageLink != null}" th:src="@{/api/file/profile.jpg}" alt="profile picture">
    
  3. th:with / ternary:

    <img th:with="image=${account.profileImageLink == null ? 'profile.jpg' : account.profileImageLink}"
         th:src="@{/api/file/{imageName}(imageName=${image})}" alt="profile picture">
    
  • Related