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
+62.4k Golang : Convert HTTP Response body to string
+20.1k Android Studio : AlertDialog and EditText to get user string input example
+35.6k Golang : Save image to PNG, JPEG or GIF format.
+20.8k Golang : Get password from console input without echo or masked
+5.6k Unix/Linux : How to open tar.gz file ?
+7.3k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+5.1k Golang : Return multiple values from function
+8.7k Golang : Sort lines of text example
+14.5k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+11k Golang : How to pipe input data to executing child process?
+11.3k Golang : Simple file scaning and remove virus example
+28.1k Golang : Read, Write(Create) and Delete Cookie example