java Thymeleaf th:each 用 th:if 过滤

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29588391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:33:21  来源:igfitidea点击:

Thymeleaf th:each filtered with th:if

javaspringspring-mvcspring-bootthymeleaf

提问by Faraj Farook

I need to iterate and create <span>elements for each of the componentin the componentsarray which has the nameof 'MATERIAL'

我需要迭代,并创建<span>针对每个元件componentcomponents,其具有阵列name'MATERIAL'

My code is as below

我的代码如下

<span th:each="component : ${body.components}" 
      th:object="${component}">
        <button th:if="*{name} == 'MATERIAL'" 
                th:text="*{title}"></button>
</span>

This code works all good until this produces a set of empty <span>elements if the nameis not equal to 'MATERIAL'. I don't want this empty <span>elements to get created.

<span>如果name不等于 ,则此代码运行良好,直到产生一组空元素'MATERIAL'。我不希望<span>创建这个空元素。

I also tried the below

我也试过下面的

<span th:each="component : ${body.components}" 
      th:object="${component}"
      th:if="*{name} == 'MATERIAL'">
         <button th:text="*{title}"></button>
</span>

This results in empty output and doesn't print anything at all. Can someone please help me on this.

这会导致空输出并且根本不打印任何内容。有人可以帮我解决这个问题。

回答by tmarwen

You should reference the iteration item property directly using a dot (.) sign instead of going through an SpEL expression evalution (*{name}) inside your html element:

您应该使用点 ( .) 符号直接引用迭代项属性,而不是通过*{name}您内部的 SpEL 表达式求值 ( )html元素:

<span th:each="component : ${body.components}" 
      th:object="${component}"
      th:if="${component.name} == 'MATERIAL'">
  <button th:text="*{title}"></button>
</span>