简体   繁体   中英

How to iterate through an attribute of a single element Grails-Gsp with the <g:each> tag

I´m working in a blog with grails, the thing is I´ve created a domain class named Post , where I defined as attributes String content, Date date, String title and since a post can have multiple comments, I also created a domain class "Comment" with: String author, File avatar, String content, Date commentDate; so I declared a one to many relationship as follows: static hasmany = [statements: Comment] in the Post domain class. Then in the blog.gsp I want to display a single post with all of it´s comments so I´m trying to use the < g:each > tag with a post as a variable, the idea is this tag to iterate through the comments list of this single post, not through all of the posts. How to achieve this?.

I'm going to use "standard" Grails variable names to avoid confusion.

If your controller sends back a Post object you can iterate through like this:

//PostController.groovy
def blog() {
    def postInstance = Post.read(params.id)
    [postInstance: postInstance]
}

//blog.gsp
${postInstance.title} //just to make sure your postInstance is correctly populated
<g:each in="${postInstance?.statements}" var="commentInstance">
    ${commentInstance.content}
<g:each>

This should work whether there are 1 or 1000 statements.

Also make sure it is

//Post.groovy
static hasMany = [statements: Comment]

You might want to have the Comment belong to the Post

//Comment.groovy
static belongsTo = [post : Post]

This makes it a bidirectional relationship.

If you are using auto binding features in Grails, make sure that the naming and the hierarchy in your classes it matching to the HTML.

debug is your best friend in this case, on the action at your server, print out the received request data.

Another note, when dealing with auto binder also, sometimes, even if the datatype in your class is defined as a list, if one element in that list is retrieved from the client side, you will notice that grails will not consider it as list.

Example,

referring to your design, 
Post
{
 hasmany = [statements: Comment]
}

If one comment found in this post, statements will be of type Comment , not Comment[] I faced this many times, maybe it is something related to my grails version i used, but it worth checking, again debug is your friend in such cases

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