Home > Software engineering >  How to pass and access a slice of struct and a struct in template
How to pass and access a slice of struct and a struct in template

Time:01-22

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?

CodePudding user response:

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 }} 
  •  Tags:  
  • go
  • Related