Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...