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
+29.2k Golang : Regular Expression for alphanumeric and underscore
+8.3k Golang : Fix go.exe is not compatible with the version of Windows you're running
+6.3k Golang : Auto-generate reply email with text/template package
+11.5k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+16.9k Golang : How to make function callback or pass value from function as parameter?
+33.5k Golang : Convert date or time stamp from string to time.Time type
+4.1k Cash Flow : 50 days to pay your credit card debt
+8.3k Golang : Select region of interest with mouse click and crop from image
+13.4k Golang : Find out mime type from bytes in buffer
+13.3k Golang : Read integer from file into array
+41k Golang : Marshal and unmarshal json.RawMessage struct example
+3.6k Python : Convert(cast) bytes to string example