37 KiB
Template functions
Table of Contents
- String Functions
- String List Functions
- Integer Math Functions
- Integer List Functions
- Date Functions
- Default Functions
- Encoding Functions
- Lists and List Functions
- Dictionaries and Dict Functions
- Type Conversion Functions
- Path and Filepath Functions
- Flow Control Functions
- UUID Functions
- Reflection Functions
- Cryptographic and Security Functions
- URL Functions
String Functions
Sprig has a number of string manipulation functions.
trim |
The `trim` function removes space from either side of a string:
The above produces |
trimAll |
Remove given characters from the front or back of a string:
The above returns |
trimSuffix |
Trim just the suffix from a string:
The above returns |
trimPrefix |
Trim just the prefix from a string:
The above returns |
upper |
Convert the entire string to uppercase:
The above returns |
lower |
Convert the entire string to lowercase:
The above returns |
title |
Convert to title case:
The above returns |
repeat |
Repeat a string multiple times:
The above returns |
substr |
Get a substring from a string. It takes three parameters:
The above returns |
trunc |
Truncate a string (and add no suffix)
The above produces The above produces |
contains |
Test to see if one string is contained inside of another:
The above returns |
hasPrefix and hasSuffix |
The `hasPrefix` and `hasSuffix` functions test whether a string has a given
prefix or suffix:
The above returns |
quote and squote |
These functions wrap a string in double quotes (`quote`) or single quotes (`squote`). |
cat |
The `cat` function concatenates multiple strings together into one, separating
them with spaces:
The above produces |
indent |
The `indent` function indents every line in a given string to the specified
indent width. This is useful when aligning multi-line strings:
The above will indent every line of text by 4 space characters. |
nindent |
The `nindent` function is the same as the indent function, but prepends a new
line to the beginning of the string.
The above will indent every line of text by 4 space characters and add a new line to the beginning. |
replace |
Perform simple string replacement.
It takes three arguments:
The above will produce |
plural |
Pluralize a string.
In the above, if the length of the string is 1, the first argument will be
printed ( The arguments are:
NOTE: Sprig does not currently support languages with more complex pluralization
rules. And |
regexMatch, mustRegexMatch |
Returns true if the input string contains any match of the regular expression.
The above produces
|
regexFindAll, mustRegexFindAll |
Returns a slice of all matches of the regular expression in the input string.
The last parameter n determines the number of substrings to return, where -1 means return all matches
The above produces
|
regexFind, mustRegexFind |
Return the first (left most) match of the regular expression in the input string
The above produces
|
regexReplaceAll, mustRegexReplaceAll |
Returns a copy of the input string, replacing matches of the Regexp with the replacement string replacement.
Inside string replacement, $ signs are interpreted as in Expand, so for instance $1 represents the text of the first submatch
The above produces
|
regexReplaceAllLiteral, mustRegexReplaceAllLiteral |
Returns a copy of the input string, replacing matches of the Regexp with the replacement string replacement
The replacement string is substituted directly, without using Expand
The above produces
|
regexSplit, mustRegexSplit |
Slices the input string into substrings separated by the expression and returns a slice of the substrings between those expression matches. The last parameter `n` determines the number of substrings to return, where `-1` means return all matches
The above produces
|
regexQuoteMeta |
Returns a string that escapes all regular expression metacharacters inside the argument text;
the returned string is a regular expression matching the literal text.
The above produces |
The Conversion Functions contain functions for converting strings. The String List Functions contains functions for working with an array of strings.
String List Functions
These function operate on or generate slices of strings. In Go, a slice is a
growable array. In Sprig, it's a special case of a list.
join |
Join a list of strings into a single string, with the given separator.
The above will produce
The above will produce |
splitList and split |
Split a string into a list of strings:
The above will return The older The above produces a map with index keys. The above produces |
splitn |
`splitn` function splits a string into a `dict` with `n` keys. It is designed to make
it easy to use template dot notation for accessing members:
The above produces a map with index keys. The above produces |
sortAlpha |
The `sortAlpha` function sorts a list of strings into alphabetical (lexicographical)
order.
It does not sort in place, but returns a sorted copy of the list, in keeping with the immutability of lists. |
Integer Math Functions
The following math functions operate on int64 values.
add |
Sum numbers with `add`. Accepts two or more inputs.
|
add1 |
To increment by 1, use `add1` |
sub |
To subtract, use `sub` |
div |
Perform integer division with `div` |
mod |
Modulo with `mod` |
mul |
Multiply with `mul`. Accepts two or more inputs.
|
max |
Return the largest of a series of integers:
This will return |
min |
Return the smallest of a series of integers.
|
floor |
Returns the greatest float value less than or equal to input value
|
ceil |
Returns the greatest float value greater than or equal to input value
|
round |
Returns a float value with the remainder rounded to the given number to digits after the decimal point.
|
randInt |
Returns a random integer value from min (inclusive) to max (exclusive).
The above will produce a random number in the range [12,30]. |
Integer List Functions
until |
The `until` function builds a range of integers.
The above generates the list This is useful for looping with |
untilStep |
Like `until`, `untilStep` generates a list of counting integers. But it allows
you to define a start, stop, and step:
The above will produce |
seq |
Works like the bash `seq` command.
* 1 parameter (end) - will generate all counting integers between 1 and `end` inclusive.
* 2 parameters (start, end) - will generate all counting integers between `start` and `end` inclusive incrementing or decrementing by 1.
* 3 parameters (start, step, end) - will generate all counting integers between `start` and `end` inclusive incrementing or decrementing by `step`.
|
Date Functions
now |
The current date/time. Use this in conjunction with other date functions. |
ago |
The `ago` function returns duration from time.Now in seconds resolution.
returns in |
date |
The `date` function formats a date.
Format the date to YEAR-MONTH-DAY: Date formatting in Go is a little bit different. In short, take this as the base date: Write it in the format you want. Above, |
dateInZone |
Same as `date`, but with a timezone.
|
duration |
Formats a given amount of seconds as a `time.Duration`.
This returns 1m35s |
durationRound |
Rounds a given duration to the most significant unit. Strings and `time.Duration`
gets parsed as a duration, while a `time.Time` is calculated as the duration since.
This return 2h This returns 3mo |
unixEpoch |
Returns the seconds since the unix epoch for a `time.Time`.
|
dateModify, mustDateModify |
The `dateModify` takes a modification and a date and returns the timestamp.
Subtract an hour and thirty minutes from the current time: If the modification format is wrong |
htmlDate |
The `htmlDate` function formats a date for inserting into an HTML date picker
input field.
|
htmlDateInZone |
Same as htmlDate, but with a timezone.
|
toDate, mustToDate |
`toDate` converts a string to a date. The first argument is the date layout and
the second the date string. If the string can't be convert it returns the zero
value.
`mustToDate` will return an error in case the string cannot be converted.
This is useful when you want to convert a string date to another format (using pipe). The example below converts "2017-12-31" to "31/12/2017". |
Default Functions
Sprig provides tools for setting default values for templates.
default |
To set a simple default value, use `default`:
In the above, if The definition of "empty" depends on type:
For structs, there is no definition of empty, so a struct will never return the default. |
empty |
The `empty` function returns `true` if the given value is considered empty, and
`false` otherwise. The empty values are listed in the `default` section.
Note that in Go template conditionals, emptiness is calculated for you. Thus,
you rarely need |
coalesce |
The `coalesce` function takes a list of values and returns the first non-empty
one.
The above returns This function is useful for scanning through multiple variables or values: The above will first check to see if |
all |
The `all` function takes a list of values and returns true if all values are non-empty.
The above returns This function is useful for evaluating multiple conditions of variables or values: The above will check http.Request is POST with tls 1.3 and http/2. |
any |
The `any` function takes a list of values and returns true if any value is non-empty.
The above returns This function is useful for evaluating multiple conditions of variables or values: The above will check http.Request method is one of GET/POST/OPTIONS. |
fromJSON, mustFromJSON |
`fromJSON` decodes a JSON document into a structure. If the input cannot be decoded as JSON the function will return an empty string.
`mustFromJSON` will return an error in case the JSON is invalid.
|
toJSON, mustToJSON |
The `toJSON` function encodes an item into a JSON string. If the item cannot be converted to JSON the function will return an empty string.
`mustToJSON` will return an error in case the item cannot be encoded in JSON.
The above returns JSON string representation of |
toPrettyJSON, mustToPrettyJSON |
The `toPrettyJSON` function encodes an item into a pretty (indented) JSON string.
The above returns indented JSON string representation of |
toRawJSON, mustToRawJSON |
The `toRawJSON` function encodes an item into JSON string with HTML characters unescaped.
The above returns unescaped JSON string representation of |
ternary |
The `ternary` function takes two values, and a test value. If the test value is
true, the first value will be returned. If the test value is empty, the second
value will be returned. This is similar to the c ternary operator.
true test valueor The above returns false test valueor The above returns |
Encoding Functions
Sprig has the following encoding and decoding functions:
b64enc/b64dec |
Encode or decode with Base64 |
b32enc/b32dec |
Encode or decode with Base32 |
Lists and List Functions
Sprig provides a simple list type that can contain arbitrary sequential lists
of data. This is similar to arrays or slices, but lists are designed to be used
as immutable data types.
Create a list of integers:
$myList := list 1 2 3 4 5
The above creates a list of [1 2 3 4 5].
first, mustFirst |
To get the head item on a list, use `first`.
|
rest, mustRest |
To get the tail of the list (everything but the first item), use `rest`.
|
last, mustLast |
To get the last item on a list, use `last`:
|
initial, mustInitial |
This compliments `last` by returning all _but_ the last element.
`initial $myList` returns `[1 2 3 4]`.
|
append, mustAppend |
Append a new item to an existing list, creating a new list.
The above would set
|
prepend, mustPrepend |
Push an element onto the front of a list, creating a new list.
The above would produce
|
concat |
Concatenate arbitrary number of lists into one.
The above would produce |
reverse, mustReverse |
Produce a new list with the reversed elements of the given list.
The above would generate the list
|
uniq, mustUniq |
Generate a list with all of the duplicates removed.
The above would produce
|
without, mustWithout |
The `without` function filters items out of a list.
The above would produce Without can take more than one filter: That would produce
|
has, mustHas |
Test to see if a list has a particular element.
The above would return
|
compact, mustCompact |
Accepts a list and removes entries with empty values.
|
slice, mustSlice |
To get partial elements of a list, use `slice list [n] [m]`. It is
equivalent of `list[n:m]`.
|
chunk |
To split a list into chunks of given size, use `chunk size list`. This is useful for pagination.
This produces list of lists |
A Note on List Internals
A list is implemented in Go as a []interface{}. For Go developers embedding
Sprig, you may pass []interface{} items into your template context and be
able to use all of the list functions on those items.
Dictionaries and Dict Functions
Sprig provides a key/value storage type called a dict (short for "dictionary",
as in Python). A dict is an unorder type.
The key to a dictionary must be a string. However, the value can be any
type, even another dict or list.
Unlike lists, dicts are not immutable. The set and unset functions will
modify the contents of a dictionary.
dict |
Creating dictionaries is done by calling the `dict` function and passing it a
list of pairs.
The following creates a dictionary with three items: |
get |
Given a map and a key, get the value from the map.
The above returns Note that if the key is not found, this operation will simply return |
set |
Use `set` to add a new key/value pair to a dictionary.
Note that |
unset |
Given a map and a key, delete the key from the map.
As with Note that if the key is not found, this operation will simply return. No error will be generated. |
hasKey |
The `hasKey` function returns `true` if the given dict contains the given key.
If the key is not found, this returns |
pluck |
The `pluck` function makes it possible to give one key and multiple maps, and
get a list of all of the matches:
The above will return a If the give key is not found in a map, that map will not have an item in the
list (and the length of the returned list will be less than the number of dicts
in the call to If the key is found but the value is an empty value, that value will be inserted. A common idiom in Sprig templates is to uses |
dig |
The `dig` function traverses a nested set of dicts, selecting keys from a list
of values. It returns a default value if any of the keys are not found at the
associated dict.
Given a dict structured like the above would return Dig can be very useful in cases where you'd like to avoid guard clauses,
especially since Go's template package's
|
keys |
The `keys` function will return a `list` of all of the keys in one or more `dict`
types. Since a dictionary is _unordered_, the keys will not be in a predictable order.
They can be sorted with `sortAlpha`.
When supplying multiple dictionaries, the keys will be concatenated. Use the |
pick |
The `pick` function selects just the given keys out of a dictionary, creating a
new `dict`.
The above returns |
omit |
The `omit` function is similar to `pick`, except it returns a new `dict` with all
the keys that _do not_ match the given keys.
The above returns |
values |
The `values` function is similar to `keys`, except it returns a new `list` with
all the values of the source `dict` (only one dictionary is supported).
The above returns |
Type Conversion Functions
The following type conversion functions are provided by Sprig:
atoi |
Convert a string to an integer. |
float64 |
Convert to a `float64`. |
int |
Convert to an `int` at the system's width. |
int64 |
Convert to an `int64`. |
toDecimal |
Convert a unix octal to a `int64`. |
toString |
Convert to a string. |
toStrings |
Convert a list, slice, or array to a list of strings. |
Only atoi requires that the input be a specific type. The others will attempt
to convert from any type to the destination type. For example, int64 can convert
floats to ints, and it can also convert strings to ints.
Path and Filepath Functions
While Sprig does not grant access to the filesystem, it does provide functions for working with strings that follow file path conventions.
Paths
Paths separated by the slash character (/), processed by the path package.
Examples:
- The Linux and
MacOS
filesystems:
/home/user/file,/etc/config; - The path component of
URIs:
https://example.com/some/content/,ftp://example.com/file/.
base |
Return the last element of a path.
The above prints "baz". |
dir |
Return the directory, stripping the last part of the path. So `dir "foo/bar/baz"` returns `foo/bar`. |
clean |
Clean up a path.
The above resolves the |
ext |
Return the file extension.
The above returns |
isAbs |
To check whether a path is absolute, use `isAbs`. |
Filepaths
Paths separated by the os.PathSeparator variable, processed by the path/filepath package.
These are the recommended functions to use when parsing paths of local filesystems, usually when dealing with local files, directories, etc.
Examples:
- Running on Linux or MacOS the filesystem path is separated by the slash character (
/):/home/user/file,/etc/config; - Running on Windows
the filesystem path is separated by the backslash character (
\):C:\Users\Username\,C:\Program Files\Application\;
osBase |
Return the last element of a filepath.
The above prints "baz" on Linux and Windows, respectively. |
osDir |
Return the directory, stripping the last part of the path. So `osDir "/foo/bar/baz"` returns `/foo/bar` on Linux, and `osDir "C:\\foo\\bar\\baz"` returns `C:\\foo\\bar` on Windows. |
osClean |
Clean up a path.
The above resolves the |
osExt |
Return the file extension.
The above returns |
osIsAbs |
To check whether a file path is absolute, use `osIsAbs`. |
Flow Control Functions
fail |
Unconditionally returns an empty `string` and an `error` with the specified
text. This is useful in scenarios where other conditionals have determined that
template rendering should fail.
|
UUID Functions
Sprig can generate UUID v4 universally unique IDs.
uuidv4 |
```
uuidv4
```
The above returns a new UUID of the v4 (randomly generated) type. |
Reflection Functions
Sprig provides rudimentary reflection tools. These help advanced template developers understand the underlying Go type information for a particular value.
Go has several primitive kinds, like string, slice, int64, and bool.
Go has an open type system that allows developers to create their own types.
Sprig provides a set of functions for each.
Kind Functions
kindOf |
Returns the kind of an object.
The above would return |
kindIs |
For simple tests (like in `if` blocks), the `kindIs` function will let you verify that a value is a particular kind:
The above will return |
Type Functions
Types are slightly harder to work with, so there are three different functions:
typeOf |
Returns the underlying type of a value: `typeOf $foo` |
typeIs |
Like `kindIs`, but for types: `typeIs "*io.Buffer" $myVal` |
typeIsLike |
Works as `typeIs`, except that it also dereferences pointers. |
Note: None of these can test whether or not something implements a given interface, since doing so would require compiling the interface in ahead of time.
deepEqual |
Returns true if two values are ["deeply equal"](https://golang.org/pkg/reflect/#DeepEqual)
Works for non-primitive types as well (compared to the built-in The above will return |
Cryptographic and Security Functions
Sprig provides a couple of advanced cryptographic functions.
sha1sum |
The `sha1sum` function receives a string, and computes it's SHA1 digest.
|
sha256sum |
The `sha256sum` function receives a string, and computes it's SHA256 digest.
The above will compute the SHA 256 sum in an "ASCII armored" format that is safe to print. |
sha512sum |
The `sha512sum` function receives a string, and computes it's SHA512 digest.
The above will compute the SHA 512 sum in an "ASCII armored" format that is safe to print. |
adler32sum |
The `adler32sum` function receives a string, and computes its Adler-32 checksum.
|
URL Functions
urlParse |
Parses string for URL and produces dict with URL parts
The above returns a dict, containing URL object: For more info, check https://golang.org/pkg/net/url/#URL |
urlJoin |
Joins map (produced by `urlParse`) to produce URL string
The above returns the following string: |