[英]grails how to check if value is in list in gsp
I'm getting a list back from my action that I want to check against another value in the GSP. 我从操作中获取了一个列表,该列表要与GSP中的另一个值进行比较。 I want to be able to see if the value is in the list that gets returned.
我希望能够查看该值是否在返回的列表中。 I know you can do direct comparison
我知道你可以直接比较
<g:if a="a">
but what I am looking for is a string in array comparison 但是我正在寻找的是数组比较中的字符串
<g:if a in [a,b,c,d]>
Need something like 需要类似的东西
<g:if test="${myList}.contains(${username})}">
Tried: 尝试过:
<g:if test="${myList.contains(username)}">
and everything is returning false (even when contains should be true) 一切都返回false(即使包含应该为true)
Test Data: 测试数据:
${myList.keySet()}
${username}
<g:if test="${failedToSync.keySet().contains(username)}">
<li>${username} yes</li>
</g:if>
<g:else>
<li>${username} no</li>
</g:else>
outputs: 输出:
[a] b
b no
[a] a
a no
Additional info: 附加信息:
"${username.stripIndent() == failedToSync.keySet()[0]}"
returns true "${username.stripIndent() == failedToSync.keySet()[0]}"
返回true
<g:if test="${(failedToSync.keySet()).contains(username.stripIndent())}"> returns false
In Groovy you can use .contains
on any collection. 在Groovy中,您可以在任何集合上使用
.contains
。 So, for your case 所以,对于你的情况
<g:if test="${['a', 'b', 'c'].contains('a')}">
...
</g:if>
You could use a custom tag if you like: 如果愿意,可以使用自定义标签:
grails-app/taglib/com/demo/StackOverflowTagLib.groovy
package com.demo
class StackOverflowTagLib {
static namespace = 'my'
// ...
def isInList = { attrs, body ->
def val = attrs.val
def list = attrs.collection
if(val in list) {
out << body()
}
}
}
grails-app/views/demo/index.gsp
<html>
<body>
<my:isInList val="Jeff" collection="${names}">
Yep, Jeff was in there.
</my:isInList>
</body>
</html>
grails-app/controllers/com/demo/DemoController.groovy
package com.demo
class DemoController {
def index() {
[names: ['Jeff', 'Betsy', 'Zack', 'Jake']]
}
}
I hope that helps. 希望对您有所帮助。
I think you have answered your own question: Yes, like 我认为您已经回答了自己的问题:是的,就像
<g:if test="${'a' in ['a','b','c','d']}">
Some Content
</g:if>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.