go-task / slim-sprig

Useful template functions for Go templates.
https://go-task.github.io/slim-sprig/
MIT License
62 stars 16 forks source link

Slim-Sprig: Template functions for Go templates Go Reference

Slim-Sprig is a fork of Sprig, but with all functions that depend on external (non standard library) or crypto packages removed. The reason for this is to make this library more lightweight. Most of these functions (specially crypto ones) are not needed on most apps, but costs a lot in terms of binary size and compilation time.

Usage

Template developers: Please use Slim-Sprig's function documentation for detailed instructions and code snippets for the >100 template functions available.

Go developers: If you'd like to include Slim-Sprig as a library in your program, our API documentation is available at pkg.go.dev.

For standard usage, read on.

Load the Slim-Sprig library

To load the Slim-Sprig FuncMap:


import (
  "html/template"

  "github.com/go-task/slim-sprig/v3"
)

// This example illustrates that the FuncMap *must* be set before the
// templates themselves are loaded.
tpl := template.Must(
  template.New("base").Funcs(sprig.FuncMap()).ParseGlob("*.html")
)

Calling the functions inside of templates

By convention, all functions are lowercase. This seems to follow the Go idiom for template functions (as opposed to template methods, which are TitleCase). For example, this:

{{ "hello!" | upper | repeat 5 }}

produces this:

HELLO!HELLO!HELLO!HELLO!HELLO!

Principles Driving Our Function Selection

We followed these principles to decide which functions to add and how to implement them: