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
Thymeleaf th:each filtered with th:if
提问by Faraj Farook
I need to iterate and create <span>
elements for each of the component
in the components
array which has the name
of 'MATERIAL'
我需要迭代,并创建<span>
针对每个元件component
中components
,其具有阵列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 name
is 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>