如何在模板中传递和访问结构体切片和结构体。

huangapple go评论73阅读模式
英文:

How to pass and access a slice of struct and a struct in template

问题

我有一个结构体类型Topic:

type Topic struct {
    Forum_id  int
    Topic_id  int
    Author    string
    Title     string
    Sub_Title string
    Body      string
}

还有一个切片类型Replay:

type Replay struct {
    Replay_ID int
    Topic_ID  int
    Author    string
    Body      string
}

我需要将这些数据传递到一个模板中,我应该如何使用只有一个变量来传递它?然后在我的模板中如何访问它?

英文:

I have a struct type Topic:

type Topic struct {
    Forum_id  int
    Topic_id  int
    Author    string
    Title     string
    Sub_Title string
    Body      string
}

And a Slice of type Replay:

type Replay struct {
    Replay_ID int
    Topic_ID  int
    Author    string
    Body      string
}

And I need to pass that data into a template, how should I do to pass it with only one variable? And then how should i access it in my template?

答案1

得分: 4

创建一个包装结构体或使用一个映射。例如:

type templateData struct {
  Topic Topic
  Replays []Replay
}

err := t.Execute(os.Stdout, templateData{topic, replays})

在你的模板中,你可以通过它们的字段名来访问它们。

{{ .Topic.Title }}
{{ range .Replays }}
{{ .Body }}
{{ end }} 
英文:

Create a wrapper struct or use a map. For example

type templateData struct {
  Topic Topic
  Replays []Replay
}

err := t.Execute(os.Stdout, templateData{topic, replays})

In your template, you can access both with their field name.

{{ .Topic.Title }}
{{ range .Replays }}
{{ .Body }}
{{ end }} 

huangapple
  • 本文由 发表于 2023年1月21日 09:37:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75190688.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定