Golang : How to pass map to html template and access the map's elements
For this tutorial, we will learn how to pass a map to text or html template and learn how to access the map's element. The first code snippet demonstrates the simplest way of creating a map, passing it to html/text template and access the map's element using the index
keyword.
NOTE : The "index"
can also be used for accessing slice and array.
NOTE : If you encounter "panic: assignment to entry in nil map"
error. Use the make
keyword to create your map instead. For example :
var templateDataMap = make(map[string]interface{})
instead of
var templateDataMap map[string]interface{}
//-- will cause panic: assignment to entry in nil map
Here you go!
package main
import (
"html/template"
"log"
"os"
)
const html = `{{ index . 1 }}
{{ index . 2 }}
{{ index . 3 }}
{{ index . 3 }}
{{ index . 2 }}
{{ index . 1 }}`
func main() {
Data := map[int]string{}
Data[1] = "abc"
Data[2] = "def"
Data[3] = "ghi"
firstTemplate, err := template.New("first").Parse(html)
if err != nil {
log.Fatalln(err)
}
err = firstTemplate.ExecuteTemplate(os.Stdout, "first", Data)
if err != nil {
log.Fatalln(err)
}
}
Output :
abc
def
ghi
ghi
def
abc
and the second code snippet demonstrates a slightly different way, but still produces the same output. The difference is that we will pass the map name as well. This will be useful in situation where we want to pass more than 1 map and able to distinguish them using the maps' names.
package main
import (
"html/template"
"log"
"os"
)
const html = `
{{ index .DataMap 1 }}
{{ index .DataMap 2 }}
{{ index .DataMap 3 }}
{{ index .DataMap 3 }}
{{ index .DataMap 2 }}
{{ index .DataMap 1 }}
`
var templateDataMap = make(map[string]interface{})
//var templateDataMap map[string]interface{} -- will cause panic: assignment to entry in nil map
func main() {
DataMap := map[int]string{}
DataMap[1] = "abc"
DataMap[2] = "def"
DataMap[3] = "ghi"
templateDataMap["DataMap"] = DataMap // pass the map's name as well
var secondTemplate = template.Must(template.New("second").Parse(html))
if err := secondTemplate.ExecuteTemplate(os.Stdout, "second", templateDataMap); err != nil {
log.Fatalln(err)
}
}
Output:
abc
def
ghi
ghi
def
abc
Hope this helps and happy coding!
Reference:
"index Returns the result of indexing its first argument by the following arguments. Thus "index x 1 2 3" is, in Go syntax, x1[2][3]. Each indexed item must be a map, slice, or array."
See also : Golang : Executing and evaluating nested loop in html template
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+16.9k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+11.1k Golang : Find age or leap age from date of birth example
+6.8k Golang : Transform lisp or spinal case to Pascal case example
+18.2k Golang : Display list of time zones with GMT
+31.6k Golang : Validate email address with regular expression
+9.3k Random number generation with crypto/rand in Go
+51.5k Golang : How to get time in milliseconds?
+5.5k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+5.2k Golang : Display advertisement images or strings on random order
+10.8k Golang : Intercept and process UNIX signals example
+16.1k Golang : Execute terminal command to remote machine example
+16.8k Golang : How to tell if a file is compressed either gzip or zip ?