In grails, using gsp how do I build a comma separated list of links from a collection of domain objects?
Basically what I want is:
<g:fancyJoin in="${myList}" var="item" separator=", ">
<g:link controller="foo" action="bar" id="${item.id}">${item.label}</g:link>
</g:fancyJoin>
开发者_JS百科and for
def mylist = [[id:1, label:"first"], [id:2, label:"second"]]
it should output:
<a href="foo/bar/1">first</a>, <a href="foo/bar/2">second</a>
The key difference between this and the existing join tag is that I need it to basically do a collect and apply tags over the initial list before performing the join operation
You shouldn't do this in a GSP. Cluttering your view with loops and conditionals makes it hard to maintain the code and forces you to test with functional tests which are quite slow. If you do this in a taglib you clean up the view and testing is very easy.
You could define a custom tag, something like:
def eachJoin = {attrs, body ->
def values = attrs.remove('in')
def var = attrs.remove('var')
def status = attrs.remove('status')
def delimiter = attrs.remove('delimiter')
values.eachWithIndex {entry, i ->
out << body([
(var ?: 'it') : entry,
(status ?: 'i') : i
])
if(delimiter && (i < values.size() - 1)) {
out << delimiter
}
}
}
Usage:
<g:eachJoin in="${myList}" var="item" delimiter=", ">
<g:link controller="foo" action="bar" id="${item.id}">${item.label}</g:link>
</g:eachJoin>
精彩评论