Im trying to create a handler which then will compile 2 templates: template.html which serves layout purposes and the actual page: config.html.
this code builds the page, but no data is passed:
func config(w http.ResponseWriter, r *http.Request) {
fpTemplate := filepath.Join("static", "template.html")
fpPage := filepath.Join("static", "config.html")
tmpl, err := template.ParseFiles(fpPage, fpTemplate)
if err != nil {
log.Println("webserver.config: " err.Error())
}
vd := ViewData{&Settings}
err = tmpl.ExecuteTemplate(w, "template.html", vd)
if err != nil {
log.Println("webserver.config: " err.Error())
}
}
and config.html like this:
{{define "title"}}
Config
{{end}}
{{define "body"}}
<p >
{{ .}}
</p>
{{end}}
, when I run this code:
func config(w http.ResponseWriter, r *http.Request) {
fpTemplate := filepath.Join("static", "template.html")
fpPage := filepath.Join("static", "config.html")
//tmpl, err := template.ParseFiles(fpPage, fpTemplate)
tmpl, err := template.New("config.html").ParseFiles(fpPage, fpTemplate)
if err != nil {
log.Println("webserver.config: " err.Error())
}
vd := ViewData{&Settings}
err = tmpl.ExecuteTemplate(w, tmpl.Name(), vd)
fmt.Println(err)
//err = tmpl.ExecuteTemplate(w, "template.html", vd)
if err != nil {
log.Println("webserver.config: " err.Error())
}
}
I get error: template: no template "config.html" associated with template "config.html" and blank black page.
What im I missing here ?
Appreciated any help!
CodePudding user response:
When you pass "vd" to ExecuteTemplate in first code, the data pass to main template and you must pass the data into "body" template when you called it on "template.html" like as:
{{ template "body" . }}