Skip to content

Instantly share code, notes, and snippets.

@ccutch
Last active February 26, 2018 23:59
Show Gist options
  • Save ccutch/c0349e97d6b106ed575d22dab3ec0e7a to your computer and use it in GitHub Desktop.
Save ccutch/c0349e97d6b106ed575d22dab3ec0e7a to your computer and use it in GitHub Desktop.
go template example
<!-- partials/header.html -->
{{define "header"}}
<header>
<h2>My website</h2>
</header>
{{end}}
<!-- homebase.html -->
<!-- Html template for homepage referenced in homepage Page struct
instance. These files can be anywhere in the project but should
be collocated with file where Page struct is defined. -->
<!-- Because we are passing a string as data we can just inpolate
it with a dot -->
<title>{{.}}</title>
{{template "header"}}
<h1>Welcome to {{.}}</h1>
// server.go
package main
import (
html "html/template"
"log"
"net/http"
)
// baseTemplate to base other templates on so partials are preloaded
var baseTemplate *html.Template
// Page struct can be reference anywhere in the project, if you are in a
// different package you have to add an import but all fields are public.
type Page struct {
// Template html file for this page
Template string
// Params generator function to produce params for the view based on
// the request
Params func(r *http.Request) interface{}
}
// ServeHTTP fulfills http.Handler interface, right now just rendering
// a template
func (p Page) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t := html.Must(baseTemplate.Clone())
html.Must(t.ParseFiles(p.Template))
if p.Params == nil {
t.Execute(w, nil)
} else {
t.ExecuteTemplate(w, p.Template, p.Params(r))
}
}
// Creating a instance of a page for the homepage, this can be done in a
// different file for more complexity or code organization
var homepage = Page{
Template: "homepage.html",
Params: func(r *http.Request) interface{} {
return "Homebase Homepage"
},
}
// Finally setup and run the server using go's http basic package
func main() {
// Loading in partial files
baseTemplate = html.New("base")
html.Must(baseTemplate.ParseGlob("partials/*.html"))
http.Handle("/", homepage)
log.Println("Server running at 127.0.0.1:8000")
http.ListenAndServe(":8000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment