Skip to content

Instantly share code, notes, and snippets.

@protosam
Created January 8, 2019 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save protosam/ad7e4ddcf8450e1ba98c6bf09d008b8e to your computer and use it in GitHub Desktop.
Save protosam/ad7e4ddcf8450e1ba98c6bf09d008b8e to your computer and use it in GitHub Desktop.
{{define "base"}}
Header, whatever....
{{template "content" .}}
Footer... whatever!
{{end}}
package main
import(
"fmt"
"os"
"errors"
"html/template"
)
// NOTE: This is a Variadic Function.
func XTPL(templatefiles ...string) (*template.Template, error) {
templates, err := template.New("").ParseFiles(templatefiles ...)
if err != nil {
return nil, err
}
tpl := templates.Lookup("base.tmpl")
if tpl == nil {
return tpl, errors.New("Base template not found.")
}
return tpl, nil
}
type MyData struct {
Things []string
}
func main(){
tpl1, err1 := XTPL(
"page1.tmpl",
"base.tmpl",
)
fmt.Println("template err?", err1)
tpl1.ExecuteTemplate(os.Stdout, "base", nil)
var stuff MyData
stuff.Things = append(stuff.Things, "Element1", "Element2", "Element3")
tpl2, err2 := XTPL(
"page2.tmpl",
"base.tmpl",
)
fmt.Println("template err?", err2)
tpl2.ExecuteTemplate(os.Stdout, "base", stuff)
var stuff2 []interface{}
stuff2 = append(stuff2, "Element1x", "Element2x", "Element3x", 1, 2, 3)
tpl3, err3 := XTPL(
"page3.tmpl",
"base.tmpl",
)
fmt.Println("template err?", err3)
tpl3.ExecuteTemplate(os.Stdout, "base", stuff2)
}
{{define "content"}}
WHATEVER! :D
{{end}}
{{define "content"}}
WHATEVER2! :D
{{range .Things}}
{{.}}
{{end}}
{{end}}
{{define "content"}}
WHATEVER2! :D
{{range .}}
{{.}}
{{end}}
{{end}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment