Search code examples
grailsjoingsptaglib

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> 

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


Solution

  • 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>