...
1# Slim-Sprig: Template functions for Go templates [](https://pkg.go.dev/github.com/go-task/slim-sprig/v3)
2
3Slim-Sprig is a fork of [Sprig](https://github.com/Masterminds/sprig), but with
4all functions that depend on external (non standard library) or crypto packages
5removed.
6The reason for this is to make this library more lightweight. Most of these
7functions (specially crypto ones) are not needed on most apps, but costs a lot
8in terms of binary size and compilation time.
9
10## Usage
11
12**Template developers**: Please use Slim-Sprig's [function documentation](https://go-task.github.io/slim-sprig/) for
13detailed instructions and code snippets for the >100 template functions available.
14
15**Go developers**: If you'd like to include Slim-Sprig as a library in your program,
16our API documentation is available [at GoDoc.org](http://godoc.org/github.com/go-task/slim-sprig).
17
18For standard usage, read on.
19
20### Load the Slim-Sprig library
21
22To load the Slim-Sprig `FuncMap`:
23
24```go
25
26import (
27 "html/template"
28
29 "github.com/go-task/slim-sprig"
30)
31
32// This example illustrates that the FuncMap *must* be set before the
33// templates themselves are loaded.
34tpl := template.Must(
35 template.New("base").Funcs(sprig.FuncMap()).ParseGlob("*.html")
36)
37```
38
39### Calling the functions inside of templates
40
41By convention, all functions are lowercase. This seems to follow the Go
42idiom for template functions (as opposed to template methods, which are
43TitleCase). For example, this:
44
45```
46{{ "hello!" | upper | repeat 5 }}
47```
48
49produces this:
50
51```
52HELLO!HELLO!HELLO!HELLO!HELLO!
53```
54
55## Principles Driving Our Function Selection
56
57We followed these principles to decide which functions to add and how to implement them:
58
59- Use template functions to build layout. The following
60 types of operations are within the domain of template functions:
61 - Formatting
62 - Layout
63 - Simple type conversions
64 - Utilities that assist in handling common formatting and layout needs (e.g. arithmetic)
65- Template functions should not return errors unless there is no way to print
66 a sensible value. For example, converting a string to an integer should not
67 produce an error if conversion fails. Instead, it should display a default
68 value.
69- Simple math is necessary for grid layouts, pagers, and so on. Complex math
70 (anything other than arithmetic) should be done outside of templates.
71- Template functions only deal with the data passed into them. They never retrieve
72 data from a source.
73- Finally, do not override core Go template functions.
View as plain text