Skip to content

Instantly share code, notes, and snippets.

@zemirco
Created January 28, 2016 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zemirco/d901356dde9a6cd71110 to your computer and use it in GitHub Desktop.
Save zemirco/d901356dde9a6cd71110 to your computer and use it in GitHub Desktop.
go nested html templates
{{ define "title" }}
a
{{ end }}
{{ define "body" }}
<p>
some content in file a
</p>
{{ end }}
{{ define "title" }}
b
{{ end }}
{{ define "body" }}
<p>
some content in file b
</p>
{{ end }}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ template "title" . }}</title>
</head>
<body>
<div class="container">
{{template "body" .}}
</div>
{{ template "footer" . }}
</body>
</html>
var (
aTmpl = parseTemplate("a.html")
bTmpl = parseTemplate("b.html")
)
func main() {
// some http router
}
func GetIndex(w http.ResponseWriter, r *http.Request) *appError {
return listTmpl.Execute(w, r, nil)
}
func parseTemplate(filename string) *appTemplate {
// HERE! somehow use the template specified by filename
tmpl := template.Must(template.ParseGlob("*.html"))
return &appTemplate{tmpl.Lookup("base.html")}
}
type appTemplate struct {
t *template.Template
}
func (tmpl *appTemplate) Execute(w http.ResponseWriter, r *http.Request, data interface{}) *appError {
d := struct {
Data interface{}
}{
Data: data,
}
if err := tmpl.t.Execute(w, d); err != nil {
return appErrorf(err, "could not write template: %v")
}
return nil
}
@mickelsonm
Copy link

should be able to set it up like this...

package main

import (
    "html/template"
    "net/http"
)

var (
    templates = template.Must(template.ParseGlob("templates/*"))
)

func base(w http.ResponseWriter, req *http.Request) {
    err := templates.ExecuteTemplate(w, "base", nil)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", base)
    http.ListenAndServe(":8000", mux)
}

Also, with your go templates...need to make sure to always define the names even for partial templates. In a.html and b.html you would need to set them up like..

{{define "a"}}
what you already have for a
{{end}}

{{define "b"}}
what you already have for b
{{end}}

something like that anyways...good luck! 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment