Executing template to a database

Trying to execute a template, and store the result in a data base. Right now, the data gets stored, but not in the form of the template I wanted.

type Data struct {
	Msg  string
	Name string
}

type DataDB struct {
	ID int
	Data 
}

func main() {
	justin := DataDB{ID:1,	Data: Data {Msg: "Justin", Name: "ABC"}}
	ruben :=  DataDB{ID:2,	Data: Data {Msg: "Ruben", Name: "tratata"}}
	petyaT := DataDB{ID:1,	Data: Data {Msg: "Petya Tereodor Pidgallo", Name: "ololol"}}

	datas := []DataDB{justin, ruben, petyaT}

	tpl, err := template.New("msgs").Parse(` {{range .}}
	 Hello {{.Data.Msg}}, my name is {{.Data.Name}}
	 {{end}}
	 `)
	if err != nil {
		panic(err)
	}

	err = tpl.Execute(os.Stdout, datas)

	if err != nil {
		log.Fatalln(err)
	}

	for _, v := range datas {
		s := []string{v.Data.Msg,v.Data.Name}
		_, err = db.Exec("INSERT INTO datadb (id, data) VALUES($1, $2)", v.ID, pq.Array(s))
		if err != nil {
			panic(err)
		}
	}
}

I executed the template to stdout and the results I got, were correct -
Hello Justin, my name is ABC
Hello Ruben, my name is tratata
Hello Petya Tereodor Pidgallo, my name is ololol.

But in my db, I got -
1"{“Justin”,“ABC”}"
2"{“Ruben”,“tratata”}"
1"{“Petya Tereodor Pidgallo”,“ololol”}"

Im trying to execute the template to my db(store the result after I execute my template, to the db).

Hope I explained correctly. Thanks in advance.

You execute the template and write the result to STDOUT. Then, later you write the string representation of each DataDB into the database. If you want to store the result of executing the template to the database, you should make s be the result of executing the template with a DataDB.

Yeah, the things that im not sure how to make “s” be the result of the executed template

Try something like this when using Template.Execute:

var tpl bytes.Buffer
if err := t.Execute(&tpl, data); err != nil {
    return err
}

result := tpl.String()

Edit: Your code could look like this:

    tpl, err := template.New("msgs").Parse(`Hello {{.Data.Msg}}, my name is {{.Data.Name}}`)
	if err != nil {
		panic(err)
	}

	for _, v := range datas {
		var buf bytes.Buffer
		if err := tpl.Execute(&buf, v); err != nil {
			log.Fatalln(err)
		}

		s := buf.String()
		fmt.Println(s)
		// Insert s into the database table.
	}

see https://play.golang.org/p/iMI0ubaAm62

1 Like

What type is the column data? Because it looks like you try to write into a JSON type column in database that can explain the output format.

Its of type character varying. Basically a string

Thanks, that did the trick

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.