Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: What's the pre-requisite to use {{ template "partial.html" . }}

Tags:

templates

go

import "os"    
import "html/template"
...    
t, _ := template.ParseFiles("login.html")
t.Execute(os.Stdout, data)
...
login.html:

{{ template "header.html" . }}
<form ....>...</form>
{{ template "footer.html" . }}

no output, no error.

If I remove those two lines of {{ template "..." . }}, I could see the part being outputed.

What's required to make {{ template "..." . }} work or am I misunderstanding html/template completely?

like image 313
Shawn Avatar asked May 16 '15 23:05

Shawn


1 Answers

You need to define a name for the file that will contain the other templates and then execute that.

login.tmpl

{{define "login"}}
<!doctype html>
<html lang="en">
..
{{template "header" .}}
</body>
</html>
{{end}}

header.tmpl

{{define "header"}}
whatever
{{end}}

Then you parse both those files

t := template.Must(template.ParseFiles("login.tmpl", "header.tmpl"))
// and then execute the template with the defined name
t.ExecuteTemplate(os.Stdout, "login", data)
like image 132
pram Avatar answered Oct 30 '22 18:10

pram