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
+10.8k Golang : Roll the dice example
+31.1k Golang : Get local IP and MAC address
+6.9k Nginx : How to block user agent ?
+5k PHP : Hide PHP version information from curl
+7.1k Golang : Create zip/ePub file without compression(use Store algorithm)
+12.1k Golang : Extract part of string with regular expression
+10.7k Golang : Replace a parameter's value inside a configuration file example
+19.7k Golang : Reset or rewind io.Reader or io.Writer
+10.2k Swift : Convert (cast) String to Integer
+25.4k Golang : How to write CSV data to file
+17k Golang : When to use init() function?
+8.1k Golang: Prevent over writing file with md5 hash