Search code examples
thymeleaf

Thymeleaf - loop though - set a variable if a value found or not


I am trying to display custom images for my list of objects. The images are stored in the database as one of the properties on the object and returned to my template in the model.

<ul>
  <li th:each="fruit : ${MyPage.fruitList}">
    <div class="field" th:onclick="'javascript:doSubmit(\'' + ${fruit.guid} + '\');'">
      <ul>
        <li th:each="property:${fruit.fruitProperties}">
          <div th:if="${property.propertyName}=='fruit_image'">
            <img alt="fruit_image" id="fruitImage" th:src="${property.propertyValue}" style="width:100px;height:100px;"></img>
          </div>
        </li>
      </ul>
      <label th:text="${fruit.name}" class="radio-label"></label> 
    </div>
  </li>
</ul>

With above code, I am able to successfully display the image that is stored as property 'fruit_image' on the fruit object in database.

Now the question I have is, how do I display a default image if the property 'fruit_image' is not present on the fruit? Is there a way i can set a flag or variable inside the 'if'?

Thank you!


Solution

  • No, there isn't a way to change a variable in Thymeleaf like that. That being said, you can use collection projection to check for the existence of that property. For example, this is how I would do a default image:

    <ul>
        <li th:each="property:${fruit.fruitProperties}">
            <div th:if="${property.propertyName}=='fruit_image'">
                <img alt="fruit_image" id="fruitImage" th:src="${property.propertyValue}" style="width:100px;height:100px;"></img>
            </div>
        </li>
    
        <li th:unless="${#lists.contains(fruit.fruitProperties.![propertyName], 'fruit_image')}">
            <div>
                <img alt="fruit_image" id="fruitImage" src="DEFAULT-IMAGE.jpg" style="width:100px;height:100px;"></img>
            </div>
        </li>
    </ul>
    

    Rather than looping through all the properties, something like this could work for you as well.

    <ul th:with="has_image = ${#lists.contains(fruit.fruitProperties.![propertyName], 'fruit_image')}">
        <li th:if="${has_image}">
            <img alt="fruit_image" id="fruitImage" th:src="${fruit.fruitProperties.^[propertyName == 'fruit_image'].propertyValue}" style="width:100px;height:100px;" />
        </li>
    
        <li th:unless="${has_image}">
            <img alt="fruit_image" id="fruitImage" src="DEFAULT-IMAGE.jpg" style="width:100px;height:100px;"></img>
        </li>
    </ul>