首页 > 解决方案 > Thymeleaf - 虽然循环 - 如果找到值则设置一个变量

问题描述

我正在尝试为我的对象列表显示自定义图像。图像作为对象的属性之一存储在数据库中,并返回到我在模型中的模板。

<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>

使用上面的代码,我能够成功地在数据库中的水果对象上显示存储为属性“fruit_image”的图像。

现在我的问题是,如果水果上不存在“fruit_image”属性,我该如何显示默认图像?有没有办法可以在“if”中设置标志或变量?

谢谢!

标签: thymeleaf

解决方案


不,没有办法像那样更改 Thymeleaf 中的变量。话虽如此,您可以使用集合投影来检查该属性是否存在。例如,这是我将如何做一个默认图像:

<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>

而不是循环遍历所有属性,这样的东西也可以为您工作。

<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>

推荐阅读