Grails/GSP: break out of <g:each>

佐手、 提交于 2019-12-04 17:58:21

Nope, not with the each clause.

I'd just write my own taglib that takes list1 and list2 and does the iteration for you, yielding back to the

<g:eachCheckedItem list1="${list1}" list2="${list2}">
    <input type="checkbox" ... checked="checked"/>
</g:eachCheckedItem>

And in your taglib class:

def eachCheckedItem = { attrs, body ->
    def list1 = attrs.list1
    def list2 = attrs.list2

    list1.findAll { list2.contains(it) }.each {
        out << body(listItem: it)  // access to listItem variable inside gsp
    }

}

Something like that (tuned to your specific problem) is easy to write, and also cleans up your gsp file quite a bit. I use these kinds of custom iterators all the time in my taglibs.

If I understood you correctly, you need something like this:

<g:each var="elem1" in="${list1}">
   <g:if test="${list2.any{it.id==elem1.id}}">
     <input type="checkbox" checked="checked" />
   </g:if>
   ...
</g:each>

There is no g:any tag, but as Ted pointed out, it would be easy to write one (left as an exercise to the reader). Then you could simplify the the inner tag to something like this:

<g:any test="${it.id==elem1.id}" in="${list2}">...</g:any>

You should do this in the model, so you then only have a simple loop in the view. Then it's just a matter of making the controller call Domain.findMyList() or whatever.

For the googlers looking for an answer to the original poster's question, there isn't a break command in gsp. There are some better responses here, the best one of which in my opinion is try and make use of .findAll { .. } to find only the set you would expect to work on prior to a 'break'.

http://markmail.org/message/tt2einl3ntwgzdep#query:grails%20gsp%20break%20out%20of%20loop+page:1+mid:nzhgwdsgkrwkurt4+state:results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!