gpt4 book ai didi

loops - 如何使用标签遍历单个元素Grails-Gsp的属性

转载 作者:行者123 更新时间:2023-12-02 15:32:43 25 4
gpt4 key购买 nike

我在一个带有grails的博客中工作,事情是我创建了一个名为Post的域类,在其中我将其定义为String content, Date date, String title属性,并且由于帖子可以包含多个注释,因此我还创建了一个域类"Comment" with: String author, File avatar, String content, Date commentDate;,因此我声明了一个与许多关系如下:Post域类中的static hasmany = [statements: Comment]。然后在blog.gsp中,我想显示一个包含所有注释的帖子,因此我试图将< g:each >标记与一个帖子一起用作变量,这个标签的想法是遍历该注释列表单个帖子,而不是所有帖子。如何实现这一目标?

最佳答案

我将使用“标准” Grails变量名来避免混淆。

如果您的 Controller 发回了Post对象,您可以像下面这样迭代:

//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>

无论有1个还是1000个语句,这都应该起作用。

还要确保它是
//Post.groovy
static hasMany = [statements: Comment]

您可能希望 Comment属于 Post
//Comment.groovy
static belongsTo = [post : Post]

这使其成为双向关系。

关于loops - 如何使用<g:each>标签遍历单个元素Grails-Gsp的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16805792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com