Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

groovy - Grails - Sorting list output without having to have a SortedSet or Comparable model?

I am banging my head up against the wall about what I think would be a very simple problem to resolve in Grails:

Say that I have shopping-cart-like model; so a class Cart that hasMany items, and each item belongsTo the cart. In general, I don't care about the order of the items in the cart - I don't care what order they're stored in, calculated in, etc. HOWEVER, I do want to DISPLAY them in the same order. It seems to me that this logic should be able to exist ENTIRELY in the view layer, but the only solutions I've been able to find tell me to declare items as a SortedSet in the model layer. This also affects my controller layer, as simple List operations such as .collect{} now require extra syntactic jumping around to keep the type conversions correct and preserve my sorting.

To me, this is nuts, so I must be missing something simple! Is there any way, for example, to do something like <g:each in="${cart.items.sort{it.name}}"> or something similar, so that I can enforce a consistent display order ONLY at the output / view layer? EDIT - See Matt's answer below; a version of this does actually work.

Thank you for any advice or pointers!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can also use the sort methods available for Collections / Maps as defined here: http://groovy.codehaus.org/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html

I personally have found it fairly easy to do this in conjunction with a <g:each/> tag in my GSP:

<!-- Books sorted by title -->
<g:each in="${ books.sort{a,b-> a.title.compareTo(b.title)} }">
    <p>Title: ${it.title}</p>
    <p>Author: ${it.author}</p>
</g:each>

For more ways you can manipulate Collections and Maps, I recommend this page and this page respectively.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...