I bought following struct:
kind Knowledge struct {
Data1 int
Data2 int
ImpData []struct {
Title string
ID string
TextS string
}
}
I unmarshall the jsoncode into var o
var o Knowledge
err = json.Unmarshal(output, &o)
if err != nil {
panic(err.Error())
}
I get the info with a for loop
for i := 0; i < len(o.ImpData); i++ {
fmt.Printf(" Check: %+v", o.ImpData[i].Title)
}
Until this level all the pieces works, however i dont know how you can excatly execute the Template with the appropriate parameters and information.
tmpl, _ := template.ParseFiles("index.html")
tmpl.Execute(w, o)
HTML:
<p model="coloration: black;"> {{ vary .ImpData }} {{ . }}</p>
Strive switching your template to one thing like this:
{{ vary .ImpData }}
<p model="coloration: black;">{{ .Title }}</p>
{{ finish }}
Right here’s a whole contrived instance to get you going:
package deal important
import (
"html/template"
"os"
"strconv"
)
kind ImpData struct {
Title string
ID string
TextS string
}
kind Knowledge struct {
Data1 int
Data2 int
ImpData []ImpData
}
var htmlTmpl = `{{ vary .ImpData }}
<p model="coloration: black;">{{ .Title }}</p>
{{ finish }}`
func important() {
// Ignoring errors for brevity. Do not actually do that.
t := template.Should(template.New("take a look at").Parse(htmlTmpl))
dat := Knowledge{}
for i := 0; i < 10; i++ {
dat.ImpData = append(dat.ImpData, ImpData{Title: "take a look at", ID: strconv.Itoa(i), TextS: "take a look at"})
}
t.Execute(os.Stdout, dat)
}
You possibly can run it on the go playground:
1 Like
Thanks on your reply and assist.
Why you declare 2 structs? This closely confuses me as i’ve a struct in struct.
in my case the unmarshalled json is in var o.
And why? dat.ImpData
I’ve o.Impdata[i].Title, o.Impdata[i].TextS
and many others as my output and this must be rendered within the html template.
My mind has a stack overflow by understanding this
Knowledge
incorporates a slice of kind ImpData
as an alternative of an nameless struct. I simply did it that means as a result of while you declare your baby struct as an nameless struct like so:
kind Knowledge struct {
Data1 int
Data2 int
ImpData []struct { // What kind is that this?
Title string
ID string
TextS string
}
}
… it makes the initialization of my contrived information extra verbose:
for i := 0; i < 10; i++ {
dat.ImpData = append(dat.ImpData, struct {
Title string
ID string
TextS string
}{"take a look at", strconv.Itoa(i), "take a look at"})
}
Nevertheless it’s in impact the identical. You possibly can run it right here with the very same Knowledge
struct as in your instance: