thymeleaf - 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 中的变量。话虽如此,您可以使用集合投影来检查该属性是否存在。例如,这是我将如何做一个默认图像:
<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>
推荐阅读
- c# - 向 C# 中变量内的字符串添加双引号时遇到问题?
- google-chrome - 验证码不显示自定义标头安全策略 referrer-policy: none
- apache - 如何为 http 和 https 使用相同的端口
- rust - 我如何要求对泛型类型的引用实现特征?
- angular - 在 IIS 中托管 Angular 4 应用程序后 HTTP 错误 500.19 内部服务器错误
- elasticsearch - ES 结果中的主数据映射
- command-line - 命令行 - 在桌面上创建 exe 文件的快捷方式
- r - 如何在 R 中抓取 JSP 页面?
- powershell - 如何排除某些用户 Powershell 密码重置脚本
- excel - 检查两列的条件公式