【问题标题】:golang not supporting struct slice depth with templategolang 不支持带模板的结构切片深度
【发布时间】:2016-11-27 06:56:38
【问题描述】:

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

在 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
}

cmets.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:扁平化嵌套结构导致切片:字段 “简历”,

我认为这是 golang 的限制。我该怎么办?

【问题讨论】:

  • 您所要求的绝对是您可以做的事情。您的模板中有一些内容:您应该发布一些简化版本。
  • 模板没有问题,因为即使我不在模板中使用 CV,它也不会显示任何内容。但是,如果我从 TweetView 中编辑掉该 CV 变量。它再次工作.. {{range .TweetSlice}} {{range .CV}} 你好 {{end}} {{end}}
  • 你确定你传递的数据是正确的吗? (顺便问一下,什么是 TweetSlice?)。我认为你应该发一个Minimal, Complete, and Verifiable example
  • @neclepsio - 感谢您的回复。这是一个可行的代码..它有 3 层结构切片。事实上,即使我在评论结构中添加“test []int”.. 它也不起作用。请让我知道我可以在哪里发布我的代码?我是新来的

标签: go go-templates


【解决方案1】:

我能够解决问题。问题出在 datastore.Get 查询上。

运行时出现以下错误

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

datastore:扁平化嵌套结构导致切片:字段 “简历”,

所以我改变了这样的查询

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

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

【讨论】:

    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 2014-03-25
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 2019-10-14
    • 2013-09-13
    相关资源
    最近更新 更多