README.md
1# Sprig: Template functions for Go templates
2[![Stability: Sustained](https://masterminds.github.io/stability/sustained.svg)](https://masterminds.github.io/stability/sustained.html)
3[![Build Status](https://travis-ci.org/Masterminds/sprig.svg?branch=master)](https://travis-ci.org/Masterminds/sprig)
4
5The Go language comes with a [built-in template
6language](http://golang.org/pkg/text/template/), but not
7very many template functions. Sprig is a library that provides more than 100 commonly
8used template functions.
9
10It is inspired by the template functions found in
11[Twig](http://twig.sensiolabs.org/documentation) and in various
12JavaScript libraries, such as [underscore.js](http://underscorejs.org/).
13
14## Usage
15
16**Template developers**: Please use Sprig's [function documentation](http://masterminds.github.io/sprig/) for
17detailed instructions and code snippets for the >100 template functions available.
18
19**Go developers**: If you'd like to include Sprig as a library in your program,
20our API documentation is available [at GoDoc.org](http://godoc.org/github.com/Masterminds/sprig).
21
22For standard usage, read on.
23
24### Load the Sprig library
25
26To load the Sprig `FuncMap`:
27
28```go
29
30import (
31 "github.com/Masterminds/sprig"
32 "html/template"
33)
34
35// This example illustrates that the FuncMap *must* be set before the
36// templates themselves are loaded.
37tpl := template.Must(
38 template.New("base").Funcs(sprig.FuncMap()).ParseGlob("*.html")
39)
40
41
42```
43
44### Calling the functions inside of templates
45
46By convention, all functions are lowercase. This seems to follow the Go
47idiom for template functions (as opposed to template methods, which are
48TitleCase). For example, this:
49
50```
51{{ "hello!" | upper | repeat 5 }}
52```
53
54produces this:
55
56```
57HELLO!HELLO!HELLO!HELLO!HELLO!
58```
59
60## Principles Driving Our Function Selection
61
62We followed these principles to decide which functions to add and how to implement them:
63
64- Use template functions to build layout. The following
65 types of operations are within the domain of template functions:
66 - Formatting
67 - Layout
68 - Simple type conversions
69 - Utilities that assist in handling common formatting and layout needs (e.g. arithmetic)
70- Template functions should not return errors unless there is no way to print
71 a sensible value. For example, converting a string to an integer should not
72 produce an error if conversion fails. Instead, it should display a default
73 value.
74- Simple math is necessary for grid layouts, pagers, and so on. Complex math
75 (anything other than arithmetic) should be done outside of templates.
76- Template functions only deal with the data passed into them. They never retrieve
77 data from a source.
78- Finally, do not override core Go template functions.
79