Instantly share code, notes, and snippets.

Embed
What would you like to do?
labstack echo template inheritance recipe
package bla
import (
"io"
"html/template"
"path/filepath"
"strings"
)
// folder structure
// views/layouts/base.hbs
// -----------------------
// [[define "layout"]] [[block "content" . ]] default content [[end]] [[end]]
// views/pages/contact.hbs
// -----------------------
// [[define "content"]] contact me [[block "ad" .]] [[end]] [[end]]
// views/pages/home.hbs
// -----------------------
// [[define "content"]] welcome [[block "ad" .]] [[end]] [[end]]
// views/shared/ad.hbs
// [[define "ad"]] buy stuff [[end]]
// init:
// var EchoTemplate = &Template{}
// echo_inst.SetRenderer(EchoTemplate)
// ReloadTemplates onStart and while developing viewstuff in handler for example
//
// useage in handler
// func H_Start(c *echo.Context) error {
// return c.Render(200, "base:home", nil)
// }
var templates map[string]*template.Template
type Template struct {
templates *template.Template // this will never be used
}
func (t *Template) Render(w io.Writer, name string, data interface{}) error {
tmpl, ok := templates[name]
if !ok {
err := errors.New2("template: name not found ->" +name, "template")
LogErrorNoContext(&err, nil)
return err
}
return tmpl.ExecuteTemplate(w, "layout", data) // layout -> defined in each layout template
}
// Load templates on program initialisation
func ReloadTemplates() {
old_maintenance_state := MAINTENANCE
MAINTENANCE = true
if templates == nil {
templates = make(map[string]*template.Template)
}
layouts, err := filepath.Glob("./views/layouts/*.hbs")
if err != nil {
err = errors.Wrap(err, "template")
LogErrorNoContext(&err, nil)
}
pages, err := filepath.Glob("./views/pages/*.hbs")
if err != nil {
err = errors.Wrap(err, "template")
LogErrorNoContext(&err, nil)
}
global_shared, err := filepath.Glob("./views/shared/*.hbs")
if err != nil {
err = errors.Wrap(err, "template")
LogErrorNoContext(&err, nil)
}
// todo: var crawl_folder = func(){}
// Generate our templates map from our layouts/ and includes/ directories
for _, layout := range layouts {
for _, page := range pages {
files := append(global_shared, layout, page)
// todo - crawl_folder func call if include is folder
layout_base :=filepath.Base(layout)
layout_short := layout_base[0:strings.LastIndex(layout_base,".")]
page_base :=filepath.Base(page)
page_short := page_base[0:strings.LastIndex(page_base,".")]
templates[layout_short+":"+ page_short] = template.Must(template.New(page_short).Delims("[[", "]]").ParseFiles(files...))
}
}
MAINTENANCE = old_maintenance_state
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment