golang 不支持模板的结构 slice 深度

标签 go go-templates

我遇到了一个独特的问题。为了学习 golang,我创建了一个 Twitter 类的网站。它有推文,每条推文都可以有评论,每个评论都可以有子评论。

在 homepage.html 中显示 struct pd

Env.Tpl.ExecuteTemplate(w, "homePage.html", pd)

其中 pd 是页面数据(为了简单起见,我删除了额外的信息)

type PageData struct {
    TweetView    []tweets.TweetView
 }

tweet.TweetView 在哪里

type TweetView struct {
    Tweet
    CV       []comments.Comment
}

comments.Comment 在哪里

type Comment struct {
    TweetID         int64
    ParentCommentID int64
    CommentID       int64
    CreatedAt     time.Time
    Name          string
    UserID        int64
    CommentMsg string
}

这行得通。但是如果我用 comment.CommentView 更改 tweetView 中的 CV .. 模板将停止显示 TweetView。

comment.CommentView是

类型 CommentView 结构 { 评论 抄送[]评论

新的 TweetView 将被定义为

type TweetView struct {
        Tweet
        CV       []comments.CommentView
    }

在尝试进行数据存储查询以将推文对象提取到 Tweetview 中时出现此错误

err := datastore.Get(ctx, tweetKey, &tweetView[v])

datastore: flattening nested structs leads to a slice of slices: field "CV",

我觉得是golang的局限性。我该怎么办?

最佳答案

我能够解决问题。问题出在数据存储区。获取查询。

运行时报错

err := datastore.Get(ctx, tweetKey, &tweetView[v])

datastore: flattening nested structs leads to a slice of slices: field "CV",

所以我把查询改成了这样

var tweetTemp Tweet
datastore.Get(ctx, tweetKey, &tweetTemp)
tweetSlice[v].Tweet = tweetTemp

如果您发现此方法有问题,请告诉我

关于golang 不支持模板的结构 slice 深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40826521/

相关文章:

go - 为什么这个 goroutine 会阻塞?

multithreading - Go-尝试创建超过一定数量的goroutine时出现段错误问题

go - Framework7与Golang模板解析器的代码冲突

templates - 如何将模板输出写入 Golang 中的文件?

kubernetes-helm - Helm 模板 .Files.Get 函数在范围内无法正常工作

go - 在 VScode 中安装 Bazel for Golang 构建应用程序

azure - go AzureAD 无效操作 : cannot indirect app. GetPasswordCredentials() ([]models.PasswordCredentialable 类型的值)

如果添加了 {{ end }},html 文件将无法工作

html - 如何在Go中使用struct中的数据生成html

go - 当结构包含获取csv数据的接口(interface)和范围时如何进行类型转换