is there any way to pass just a variable (string, int, bool) into template. For example (something similar):
import (
"html/template"
)
func main() {
....
tmpl := template.Must(template.ParseFiles("templates/index.html"))
mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
varmap := map[string]interface{}{
"var1": "value",
"var2": 100,
}
tmpl.ExecuteTemplate(rw, "index", varmap)
})
// content of index.html
{{define "index"}}
{{var1}} is equal to {{var2}}
{{end}}
}
Yes just use the dot in front of it:
http://play.golang.org/p/7NXu9SDiik
package main
import (
"html/template"
"log"
"os"
)
var tmplString = ` // content of index.html
{{define "index"}}
{{.var1}} is equal to {{.var2}}
{{end}}
`
func main() {
tmpl, err := template.New("test").Parse(tmplString)
if err != nil {
log.Fatal(err)
}
varmap := map[string]interface{}{
"var1": "value",
"var2": 100,
}
tmpl.ExecuteTemplate(os.Stdout, "index", varmap)
}
It is possible to pass just a simple value of any type. If you do so, you can refer to it in the template as {{.}}
.
Here is an example (try it on the Go Playgound ):
s := "<html><body>Value passed: {{.}}</body></html>\n"
tmpl := template.Must(template.New("test").Parse(s))
tmpl.Execute(os.Stdout, false)
tmpl.Execute(os.Stdout, 1)
tmpl.Execute(os.Stdout, "me")
Output:
<html><body>Value passed: false</body></html>
<html><body>Value passed: 1</body></html>
<html><body>Value passed: me</body></html>
Try fasttemplate [1]. It accepts a map of placeholders' substitution values. And it works faster than html/template on simple templates.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.