blob: ae623220864e367f9ebe6275e070ec795313d256 [file] [log] [blame]
package main
import (
"fmt"
"html/template"
"net/http"
"github.com/golang/glog"
"code.hackerspace.pl/hscloud/hswaw/site/templates"
)
// parseTemplates parses a set of templates from
// //hswaw/site/templates/$name.html into a Go HTML template. Typical Go text
// templating ordering behaviour applies (this basically replicates
// template.ParseFiles, but for statically embedded files instead).
func parseTemplates(names ...string) (*template.Template, error) {
if len(names) == 0 {
return nil, fmt.Errorf("at least one template must be given")
}
var t *template.Template
for _, n := range names {
path := fmt.Sprintf("hswaw/site/templates/%s.html", n)
data, ok := templates.Data[path]
if !ok {
return nil, fmt.Errorf("template %q (%s) not found", n, path)
}
s := string(data)
if t == nil {
t = template.New(n)
}
_, err := t.Parse(s)
if err != nil {
return nil, fmt.Errorf("template %q could not be parsed: %w", n, err)
}
}
return t, nil
}
var (
tmplAbout = template.Must(parseTemplates("basic", "about"))
tmplAboutEn = template.Must(parseTemplates("basic", "about_en"))
)
// render attempts to render a given Go template with data into the HTTP
// response writer, and logs a warning if anything goes wrong.
func render(w http.ResponseWriter, t *template.Template, data interface{}) {
if err := t.Execute(w, data); err != nil {
glog.Warningf("Rendering %v failed: %v", t, err)
}
}
// handleAbout handles rendering the about page at /about
func (s *service) handleAbout(w http.ResponseWriter, r *http.Request) {
render(w, tmplAbout, nil)
}
// handleAboutEn handles rendering the about page at /about_en
func (s *service) handleAboutEn(w http.ResponseWriter, r *http.Request) {
render(w, tmplAboutEn, nil)
}