/view

🕶 A superset of the standard html/template package

Primary LanguageGoMIT LicenseMIT

gowww view GoDoc Build Coverage Go Report Status Stable

Package view provides a superset of the standard html/template package.
It allows to keep global data for templates and parse strings, files and directories (also recursively).

Installing

  1. Get package:

    go get -u github.com/gowww/view
  2. Import it in your code:

    import "github.com/gowww/view"

Usage

Parsing

Use New to make a new view unit:

v := view.New()

Use Data to add global data for view templates:

v.Data(view.Data{"app": "App"})
v.Data(view.Data{"foobar": "Foobar"})

Use Funcs to add functions for view templates:

v.Funcs(view.Funcs{
	"pathescape": url.PathEscape,
	"trim":       strings.Trim,
})

Use Parse to parse text directly:

v.Parse("<h1>{{.app}} — {{.title}}</h1><p>{{.foobar}}</p>")

Use ParseFiles to parse names files:

v.ParseFiles("main.gohtml", "admin.gohtml")

Use ParseGlob to parse files matching a path pattern:

v.ParseGlob("views/*.gohtml")

Use ParseDir to recursively parse all files from a directory:

v.ParseDir("views")

All this can be chained and called multiple times:

v := view.New().
	Data(data1).
	Data(data2).
	Funcs(funcs1).
	Funcs(funcs2).
	Parse(tmpl)

Execution

Use Execute to execute main template:

w := new(bytes.Buffer)
v.Execute(w, Data{"title": "Example"})

Use ExecuteTemplate to execute a named template:

w := new(bytes.Buffer)
v.ExecuteTemplate(w, "home", Data{"title": "Example"})

Built-in functions

In addition to the functions provided by the standard template package, these functions are also available out of the box:

Function Description Usage
googlefonts Sets an HTML link to Google Fonts's stylesheet of the given font(s). {{googlefonts "Open+Sans:400,700|Spectral"}}
nl2br Converts \n to HTML <br>. {{nl2br "line one\nline two"}}
safehtml Prevents string to be escaped. Be careful. {{safehtml "<strong>word</strong>"}}
script Sets HTML script tag for the given script source. {{script "/static/main.js"}}
style Sets HTML link tag for the given stylesheet. {{style "/static/main.css"}}