i have template in go using http/template
package. how iterate on both keys , values in template?
example code :
template := ` <html> <body> <h1>test match</h1> <ul> {{range .}} <li> {{.}} </li> {{end}} </ul> </body> </html>` datamap["something"] = 124 datamap["something else"] = 125 t, _ := template.parse(template) t.execute(w,datamap)
how access key in {{range}}
in template
one thing try using range
assign 2 variables - 1 key, 1 value. per this change (and docs), keys returned in sorted order possible. here example using data:
package main import ( "html/template" "os" ) func main() { // here 'unpack' map key , value tem := ` <html> <body> <h1>test match</h1> <ul> {{range $k, $v := . }} <li> {{$k}} : {{$v}} </li> {{end}} </ul> </body> </html>` // create map , add data datamap := make(map[string]int) datamap["something"] = 124 datamap["something else"] = 125 // create new template, parse , add map t := template.new("my template") t, _ = t.parse(tem) t.execute(os.stdout, datamap) }
there better ways of handling it, has worked in (very simple) use cases :)
Comments
Post a Comment