Skip to content

Instantly share code, notes, and snippets.

@heatxsink
Last active July 20, 2020 03:37
Show Gist options
  • Save heatxsink/67e1d098f63425efd350e4625c0b13dc to your computer and use it in GitHub Desktop.
Save heatxsink/67e1d098f63425efd350e4625c0b13dc to your computer and use it in GitHub Desktop.
Nested go.rice templates example using golang "net/http" webserver.

To run this example ...

  • mkdir templates
  • mv *.tmpl templates/
  • go get github.com/GeertJohan/go.rice
  • go generate
  • go run main.go
{{ define "away" }}
<!DOCTYPE html>
<html>
<head>
{{ template "header" . }}
</head>
<body>
<h1>AWAY</h1>
</body>
</html>
{{ end }}
{{ define "header" }}
<title>{{ .title }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
{{ end }}
{{ define "home" }}
<!DOCTYPE html>
<html>
<head>
{{ template "header" . }}
</head>
<body>
<h1>HOME</h1>
</body>
</html>
{{ end }}
package main
//go:generate rice embed-go
import (
"fmt"
"html/template"
"net/http"
rice "github.com/GeertJohan/go.rice"
)
var (
templates map[string]*template.Template
)
func root(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/home", 302)
}
func home(w http.ResponseWriter, r *http.Request) {
ctx := make(map[string]interface{})
ctx["title"] = "HOME"
renderTemplate(w, "home", ctx)
}
func away(w http.ResponseWriter, r *http.Request) {
ctx := make(map[string]interface{})
ctx["title"] = "AWAY"
renderTemplate(w, "away", ctx)
}
func renderTemplate(w http.ResponseWriter, name string, p interface{}) {
w.Header().Set("Content-Type", "text/html")
tmpl := templates[name]
err := tmpl.Execute(w, p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func combineTemplates(path string) (string, error) {
box, err := rice.FindBox("templates/")
if err != nil {
return "", err
}
header, err := box.String("header.tmpl")
if err != nil {
return "", err
}
tmpl, err := box.String(path)
if err != nil {
return "", err
}
return fmt.Sprintf("%s\n%s", header, tmpl), nil
}
func loadTemplates() (map[string]*template.Template, error) {
templates := make(map[string]*template.Template)
home, err := combineTemplates("home.tmpl")
if err != nil {
return templates, err
}
templateHome := template.Must(template.New("home").Parse(home))
templates["home"] = templateHome
away, err := combineTemplates("away.tmpl")
if err != nil {
return templates, err
}
templateAway := template.Must(template.New("away").Parse(away))
templates["away"] = templateAway
return templates, nil
}
func main() {
var err error
templates, err = loadTemplates()
if err != nil {
fmt.Println(err)
}
http.HandleFunc("/", home)
http.HandleFunc("/home", home)
http.HandleFunc("/away", away)
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment