简体   繁体   English

在grails中,如何使用gsp从一组域对象中构建一个用逗号分隔的链接列表?

[英]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. 您不应该在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. 如果在taglib中执行此操作,则可以清理视图,并且测试非常容易。

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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