简体   繁体   中英

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM