html icon indicating copy to clipboard operation
html copied to clipboard

Go package for loading, composing and rendering HTML templates

html Build Status Coverage Status GoDoc

This Go package can load, compose and render HTML templates. It's a small layer on top of 'html/template'.

Features

  • fluent API: easily compose templates into sets
  • auto-reloading: reload templates on page refresh
  • redefinition: define a default and overwrite it later
  • validation: ensure completeness at time of creation (not rendering)
  • helper functions: e.g. use 'runTemplate' to execute an arbitrary template
  • caching: templates are only parsed once

Example

import "github.com/stephanos/html"

// specify template source directories, enable auto-reload
conf := html.Config{Directories: []string{"views"}, AutoReload: true}

// scan for available templates
loader, _ := html.NewLoader(conf)

// create two sets: a re-usable and a specific one
baseSet := loader.NewSet().Add("layout", "partials/header", "partials/footer")
helloSet := loader.NewSet().AddSet(baseSet).Add("pages/hello")

// create executable view, making sure all template placeholders are defined
view := helloSet.ViewMust()

// execute the template and print the result to a Writer
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
    view.Write(w, "World") 
})

ToDos

  • render any error to HTML (+ display snippet of template source)
  • add method to trigger a re-build of all views
  • allow custom template file extension (other than .html)
  • allow custom template parser

Install

go get github.com/stephanos/html

Documentation

godoc.org

License

MIT (see LICENSE).