Tired this https://github.com/golang-samples/template/blob/master/parseglob/main.go but server is shutting down forcefully. 1)main.go package main
import (
"log"
"os"
"text/template"
)
func main() {
t := template.New("main.tmpl")
t = template.Must(t.ParseGlob("templates/*.tmpl"))
err := t.Execute(os.Stdout, nil)
if err != nil {
log.Fatalf("template execution: %s", err)
}
}
2) main.tmpl
{{template "header"}}
<p>main content</p>
{{template "footer"}}
3) header.html
{{define "header"}}
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
{{end}}
4) footor.html
{{define "footer"}}
</body>
</html>
{{end}}
Any other useful link ?
based on my below code,
i created a howto here: http://javatogo.blogspot.com/2013/06/howto-render-multiple-templates-with-go.html
here is an example how to render multiple templates:
const rootPageTemplateHtml = `
<!DOCTYPE html>
<html>
<head>
<title>{{.PageTitle}}</title>
</head>
<body>
{{template "pageMenu" .}}
{{template "pageContent" .}}
{{template "pageFooter" .}}
</body>
</html>
`
const pageMenuTemplateHtml = `
<div>
menu: {{.PageName}}
</div>
`
type PageContent struct {
PageName string
PageContent interface{}
PageTitle string
}
func initTemplate(tmpl *template.Template) {
*tmpl = *template.Must(template.New("rootPage").Parse(rootPageTemplateHtml))
tmpl.New("pageHeader").Parse(``)
tmpl.New("pageMenu").Parse(pageMenuTemplateHtml)
tmpl.New("pageFooter").Parse(``)
}
func execTemplate(tmpl *template.Template, w *http.ResponseWriter, pc *PageContent) {
if err := tmpl.Execute(*w, *pc); err != nil {
http.Error(*w, err.Error(), http.StatusInternalServerError)
}
}
now lets add the first page:
const welcomeTemplateHTML = `
<div>welcome page</div>
`
var welcomePage *template.Template
func initWelcomePageTemplate() {
if nil == welcomePage {
welcomePage = new(template.Template)
initTemplate(welcomePage)
welcomePage.New("pageContent").Parse(welcomeTemplateHTML)
}
}
func renderWelcomePage(w *http.ResponseWriter, pc *PageContent) {
initWelcomePageTemplate()
execTemplate(welcomePage, w, pc)
}
and a second page:
const linksTemplateHTML = `
<div>second page</div>
`
var secondPage *template.Template
func initSecondPageTemplate() {
if nil == secondPage {
secondPage = new(template.Template)
initTemplate(secondPage)
secondPage.New("pageContent").Parse(secondTemplateHTML)
}
}
func renderSecondPage(w *http.ResponseWriter, pc *PageContent) {
initSecondPageTemplate()
execTemplate(secondPage, w, pc)
}
to execute this different templates just add to your handler:
func init() {
http.HandleFunc("/", welcome)
http.HandleFunc("/second", second)
}
func welcome(w http.ResponseWriter, r *http.Request) {
pc := PageContent{"/", nil, "Welcome Page Title"}
renderWelcomePage(&w, &pc)
}
func second(w http.ResponseWriter, r *http.Request) {
pc := PageContent{"/second", nil, "Second Page Title"}
renderSecondPage(&w, &pc)
}
now you can add as many files as you want