sprig
Sprig provides tons of utilitary functions to be used inside templates.
abbrev¶
Truncate a string with ellipses (...
)
Parameters:
- max length
- the string
The above returns he...
, since it counts the width of the ellipses against the
maximum length.
abbrevboth¶
Abbreviate both sides:
the above produces ...5678...
It takes:
- left offset
- max length
- the string
add¶
Sum numbers with add
. Accepts two or more inputs.
add1¶
To increment by 1, use add1
add1f¶
To increment a float by 1, use add1f
addf¶
Sum floats with addf
. Accepts two or more inputs.
adler32sum¶
Computes adler32 checksum
ago¶
The ago
function returns duration from time.Now in seconds resolution.
returns in time.Duration
String() format
all¶
all
returns true if empty(x)
is false for all values x in the list.
If the list is empty, return true.
any¶
any
returns true if empty(x)
is false for any x in the list.
If the list is empty, return false.
append¶
Append a new item to an existing list, creating a new list.
The above would set $new
to [1 2 3 4 5 6]
. $myList
would remain unaltered.
append
panics if there is a problem while mustAppend
returns an error to the
template engine if there is a problem.
atoi¶
atoi
: Convert a string to an integer.
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.
b32dec¶
Sprig has the following encoding and decoding functions:
b32enc
/b32dec
: Encode or decode with Base32
b32enc¶
Sprig has the following encoding and decoding functions:
b32enc
/b32dec
: Encode or decode with Base32
b64dec¶
Sprig has the following encoding and decoding functions:
b64enc
/b64dec
: Encode or decode with Base64
b64enc¶
Sprig has the following encoding and decoding functions:
b64enc
/b64dec
: Encode or decode with Base64
base¶
Return the last element of a path.
The above prints "baz"
bcrypt¶
bcrypt
returns the bcrypt hash of a password using bcrypt library with the DefaultCost.
biggest¶
No documentation for this function
buildCustomCert¶
The buildCustomCert
function allows customizing the certificate.
It takes the following string parameters:
- A base64 encoded PEM format certificate
- A base64 encoded PEM format private key
It returns a certificate object with the following attributes:
Cert
: A PEM-encoded certificateKey
: A PEM-encoded private key
Example:
Note that the returned object can be passed to the genSignedCert
function
to sign a certificate using this CA.
camelcase¶
Convert string from snake_case to CamelCase
This above will produce HttpServer
.
cat¶
The cat
function concatenates multiple strings together into one, separating
them with spaces:
The above produces hello beautiful world
ceil¶
Returns the greatest float value greater than or equal to input value
ceil 123.001
will return 124.0
chunk¶
To split a list into chunks of given size, use chunk size list
. This is useful for pagination.
This produces list of lists [ [ 1 2 3 ] [ 4 5 6 ] [ 7 8 ] ]
.
clean¶
Clean up a path.
The above resolves the ..
and returns foo/baz
coalesce¶
The coalesce
function takes a list of values and returns the first non-empty
one.
The above returns 1
.
This function is useful for scanning through multiple variables or values:
The above will first check to see if .name
is empty. If it is not, it will return
that value. If it is empty, coalesce
will evaluate .parent.name
for emptiness.
Finally, if both .name
and .parent.name
are empty, it will return Matt
.
compact¶
Accepts a list and removes entries with empty values.
compact
will return a new list with the empty (i.e., "") item removed.
compact
panics if there is a problem and mustCompact
returns an error to the
template engine if there is a problem.
concat¶
Concatenate arbitrary number of lists into one.
The above would produce [1 2 3 4 5 6 7 8]
. $myList
would remain unaltered.
contains¶
Test to see if one string is contained inside of another:
The above returns true
because catch
contains cat
.
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, 2006-01-02
is the same date, but
in the format we want.
dateInZone¶
Same as date
, but with a timezone.
dateModify¶
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 dateModify
will return the date unmodified. mustDateModify
will return an error otherwise.
date_in_zone¶
Same as date
, but with a timezone.
date_modify¶
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 dateModify
will return the date unmodified. mustDateModify
will return an error otherwise.
decryptAES¶
The decryptAES
function receives a base64 string encoded by the AES-256 CBC
algorithm and returns the decoded text.
deepCopy¶
The deepCopy
and mustDeepCopy
functions takes a value and makes a deep copy
of the value. This includes dicts and other structures. deepCopy
panics
when there is a problem while mustDeepCopy
returns an error to the template
system when there is an error.
deepEqual¶
deepEqual
returns true if two values are "deeply equal"
Works for non-primitive types as well (compared to the built-in eq
).
The above will return true
default¶
To set a simple default value, use default
:
In the above, if .Bar
evaluates to a non-empty value, it will be used. But if
it is empty, foo
will be returned instead.
The definition of "empty" depends on type:
- Numeric: 0
- String: ""
- Lists:
[]
- Dicts:
{}
- Boolean:
false
- And always
nil
(aka null)
For structs, there is no definition of empty, so a struct will never return the default.
derivePassword¶
The derivePassword
function can be used to derive a specific password based on
some shared "master password" constraints. The algorithm for this is
well specified.
Note that it is considered insecure to store the parts directly in the template.
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:
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 "curator"
. If the dict lacked even a user
field,
the result would be "guest"
.
Dig can be very useful in cases where you'd like to avoid guard clauses,
especially since Go's template package's and
doesn't shortcut. For instance
and a.maybeNil a.maybeNil.iNeedThis
will always evaluate
a.maybeNil.iNeedThis
, and panic if a
lacks a maybeNil
field.)
dig
accepts its dict argument last in order to support pipelining. For instance:
kindIs¶
There are two Kind functions: kindOf
returns the kind of an object.
The above would return string
. For simple tests (like in if
blocks), the
isKind
function will let you verify that a value is a particular kind:
The above will return true
kindOf¶
There are two Kind functions: kindOf
returns the kind of an object.
The above would return string
. For simple tests (like in if
blocks), the
isKind
function will let you verify that a value is a particular kind:
The above will return true
last¶
To get the last item on a list, use last
:
last $myList
returns 5
. This is roughly analogous to reversing a list and
then calling first
.
list¶
No documentation for this function
lower¶
Convert the entire string to lowercase:
The above returns hello
max¶
Return the largest of a series of integers:
This will return 3
:
maxf¶
Floats version of max
merge¶
Merge two or more dictionaries into one, giving precedence to the dest dictionary:
This is a deep merge operation but not a deep copy operation. Nested objects that
are merged are the same instance on both dicts. If you want a deep copy along
with the merge than use the deepCopy
function along with merging. For example,
mustMerge
will return an error in case of unsuccessful merge.
mergeOverwrite¶
Merge two or more dictionaries into one, giving precedence from right to left, effectively overwriting values in the dest dictionary:
Given:
will result in:
This is a deep merge operation but not a deep copy operation. Nested objects that
are merged are the same instance on both dicts. If you want a deep copy along
with the merge than use the deepCopy
function along with merging. For example,
mustMergeOverwrite
will return an error in case of unsuccessful merge.
min¶
Return the smallest of a series of integers.
min 1 2 3
will return 1
minf¶
Floats version of min
mod¶
Modulo with mod
mul¶
Multiply with mul
. Accepts two or more inputs.
mulf¶
Floats version of mul
mustAppend¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustChunk¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustCompact¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustDateModify¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustDeepCopy¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustFirst¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustFromJson¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustHas¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustInitial¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustLast¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustMerge¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustMergeOverwrite¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustPrepend¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustPush¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustRegexFind¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustRegexFindAll¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustRegexMatch¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustRegexReplaceAll¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustRegexReplaceAllLiteral¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustRegexSplit¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustRest¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustReverse¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustSlice¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustToDate¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustToJson¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustToPrettyJson¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustToRawJson¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustUniq¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
mustWithout¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
must_date_modify¶
"mustXXX" function returns an error while original XXX functions panics if something goes wrong
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.
nospace¶
Remove all whitespace from a string.
The above returns helloworld
now¶
The current date/time. Use this in conjunction with other date functions.
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 {name2: value2}
osBase¶
Return the last element of a filepath.
The above prints "baz" on Linux and Windows, respectively.
osClean¶
Clean up a path.
The above resolves the ..
and returns foo/baz
on Linux and C:\\foo\\baz
on Windows.
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.
osExt¶
Return the file extension.
The above returns .bar
on Linux and Windows, respectively.
osIsAbs¶
To check whether a file path is absolute, use osIsAbs
.
pick¶
The pick
function selects just the given keys out of a dictionary, creating a
new dict
.
The above returns {name1: value1, name2: value2}
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 list
containing every found value ([value1 otherValue1]
).
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 pluck
.
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 pluck... | first
to get the first
matching key out of a collection of dictionaries.
plural¶
Pluralize a string.
In the above, if the length of the string is 1, the first argument will be
printed (one anchovy
). Otherwise, the second argument will be printed
(many anchovies
).
The arguments are:
- singular string
- plural string
- length integer
NOTE: Sprig does not currently support languages with more complex pluralization
rules. And 0
is considered a plural because the English language treats it
as such (zero anchovies
). The Sprig developers are working on a solution for
better internationalization.
prepend¶
Push an element onto the front of a list, creating a new list.
The above would produce [0 1 2 3 4 5]
. $myList
would remain unaltered.
prepend
panics if there is a problem while mustPrepend
returns an error to the
template engine if there is a problem.
push¶
No documentation for this function
quote¶
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 hello beautiful world
randAlpha¶
These four functions generate cryptographically secure (uses crypto/rand
)
random strings, but with different base character sets:
randAlphaNum
uses0-9a-zA-Z
randAlpha
usesa-zA-Z
randNumeric
uses0-9
randAscii
uses all printable ASCII characters
Each of them takes one parameter: the integer length of the string.
The above will produce a random string with three digits.
randAlphaNum¶
These four functions generate cryptographically secure (uses crypto/rand
)
random strings, but with different base character sets:
randAlphaNum
uses0-9a-zA-Z
randAlpha
usesa-zA-Z
randNumeric
uses0-9
randAscii
uses all printable ASCII characters
Each of them takes one parameter: the integer length of the string.
The above will produce a random string with three digits.
randAscii¶
These four functions generate cryptographically secure (uses crypto/rand
)
random strings, but with different base character sets:
randAlphaNum
uses0-9a-zA-Z
randAlpha
usesa-zA-Z
randNumeric
uses0-9
randAscii
uses all printable ASCII characters
Each of them takes one parameter: the integer length of the string.
The above will produce a random string with three digits.
randBytes¶
The randBytes
function accepts a count N
and generates a cryptographically
secure (uses crypto/rand
) random sequence of N
bytes. The sequence is
returned as a base64 encoded string.
randInt¶
Returns a random integer value from min (inclusive) to max (exclusive).
randNumeric¶
These four functions generate cryptographically secure (uses crypto/rand
)
random strings, but with different base character sets:
randAlphaNum
uses0-9a-zA-Z
randAlpha
usesa-zA-Z
randNumeric
uses0-9
randAscii
uses all printable ASCII characters
Each of them takes one parameter: the integer length of the string.
The above will produce a random string with three digits.
regexFind¶
Return the first (left most) match of the regular expression in the input string
The above produces d1
regexFind
panics if there is a problem and mustRegexFind
returns an error to the
template engine if there is a problem.
regexFindAll¶
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 [2 4 6 8]
regexFindAll
panics if there is a problem and mustRegexFindAll
returns an error to the
template engine if there is a problem.
regexMatch¶
Returns true if the input string contains any match of the regular expression.
The above produces true
regexMatch
panics if there is a problem and mustRegexMatch
returns an error to the
template engine if there is a problem.
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 1\.2\.3
regexReplaceAll¶
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 -W-xxW-
regexReplaceAll
panics if there is a problem and mustRegexReplaceAll
returns an error to the
template engine if there is a problem.
regexReplaceAllLiteral¶
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 -${1}-${1}-
regexReplaceAllLiteral
panics if there is a problem and mustRegexReplaceAllLiteral
returns an error to the
template engine if there is a problem.
regexSplit¶
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 [pi a]
regexSplit
panics if there is a problem and mustRegexSplit
returns an error to the
template engine if there is a problem.
repeat¶
Repeat a string multiple times:
The above returns hellohellohello
replace¶
Perform simple string replacement.
It takes three arguments:
- string to replace
- string to replace with
- source string
The above will produce I-Am-Henry-VIII
rest¶
To get the tail of the list (everything but the first item), use rest
.
rest $myList
returns [2 3 4 5]
rest
panics if there is a problem while mustRest
returns an error to the
template engine if there is a problem.
reverse¶
Produce a new list with the reversed elements of the given list.
The above would generate the list [5 4 3 2 1]
.
reverse
panics if there is a problem while mustReverse
returns an error to the
template engine if there is a problem.
round¶
Returns a float value with the remainder rounded to the given number to digits after the decimal point.
round 123.555555 3
will return 123.556
semver¶
The semver
function parses a string into a Semantic Version:
If the parser fails, it will cause template execution to halt with an error.
At this point, $version
is a pointer to a Version
object with the following
properties:
$version.Major
: The major number (1
above)$version.Minor
: The minor number (2
above)$version.Patch
: The patch number (3
above)$version.Prerelease
: The prerelease (alpha.1
above)$version.Metadata
: The build metadata (123
above)$version.Original
: The original version as a string
Additionally, you can compare a Version
to another version
using the Compare
function:
The above will return -1
.
The return values are:
-1
if the given semver is greater than the semver whoseCompare
method was called1
if the version who'sCompare
function was called is greater.0
if they are the same version
(Note that in SemVer, the Metadata
field is not compared during version
comparison operations.)
semverCompare¶
A more robust comparison function is provided as semverCompare
. This version
supports version ranges:
semverCompare "1.2.3" "1.2.3"
checks for an exact matchsemverCompare "^1.2.0" "1.2.3"
checks that the major and minor versions match, and that the patch number of the second version is greater than or equal to the first parameter.
The SemVer functions use the Masterminds semver library, from the creators of Sprig.
Basic Comparisons¶
There are two elements to the comparisons. First, a comparison string is a list
of space or comma separated AND comparisons. These are then separated by || (OR)
comparisons. For example, ">= 1.2 < 3.0.0 || >= 4.2.3"
is looking for a
comparison that's greater than or equal to 1.2 and less than 3.0.0 or is
greater than or equal to 4.2.3.
The basic comparisons are:
=
: equal (aliased to no operator)!=
: not equal>
: greater than<
: less than>=
: greater than or equal to<=
: less than or equal to
Note, according to the Semantic Version specification pre-releases may not be API compliant with their release counterpart. It says,
Working With Prerelease Versions¶
Pre-releases, for those not familiar with them, are used for software releases
prior to stable or generally available releases. Examples of prereleases include
development, alpha, beta, and release candidate releases. A prerelease may be
a version such as 1.2.3-beta.1
while the stable release would be 1.2.3
. In the
order of precedence, prereleases come before their associated releases. In this
example 1.2.3-beta.1 < 1.2.3
.
According to the Semantic Version specification prereleases may not be API compliant with their release counterpart. It says,
A pre-release version indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its associated normal version.
SemVer comparisons using constraints without a prerelease comparator will skip
prerelease versions. For example, >=1.2.3
will skip prereleases when looking
at a list of releases while >=1.2.3-0
will evaluate and find prereleases.
The reason for the 0
as a pre-release version in the example comparison is
because pre-releases can only contain ASCII alphanumerics and hyphens (along with
.
separators), per the spec. Sorting happens in ASCII sort order, again per the
spec. The lowest character is a 0
in ASCII sort order
(see an ASCII Table)
Understanding ASCII sort ordering is important because A-Z comes before a-z. That
means >=1.2.3-BETA
will return 1.2.3-alpha
. What you might expect from case
sensitivity doesn't apply here. This is due to ASCII sort ordering which is what
the spec specifies.
Hyphen Range Comparisons¶
There are multiple methods to handle ranges and the first is hyphens ranges. These look like:
1.2 - 1.4.5
which is equivalent to>= 1.2 <= 1.4.5
2.3.4 - 4.5
which is equivalent to>= 2.3.4 <= 4.5
Wildcards In Comparisons¶
The x
, X
, and *
characters can be used as a wildcard character. This works
for all comparison operators. When used on the =
operator it falls
back to the patch level comparison (see tilde below). For example,
1.2.x
is equivalent to>= 1.2.0, < 1.3.0
>= 1.2.x
is equivalent to>= 1.2.0
<= 2.x
is equivalent to< 3
*
is equivalent to>= 0.0.0
Tilde Range Comparisons (Patch)¶
The tilde (~
) comparison operator is for patch level ranges when a minor
version is specified and major level changes when the minor number is missing.
For example,
~1.2.3
is equivalent to>= 1.2.3, < 1.3.0
~1
is equivalent to>= 1, < 2
~2.3
is equivalent to>= 2.3, < 2.4
~1.2.x
is equivalent to>= 1.2.0, < 1.3.0
~1.x
is equivalent to>= 1, < 2
Caret Range Comparisons (Major)¶
The caret (^
) comparison operator is for major level changes once a stable
(1.0.0) release has occurred. Prior to a 1.0.0 release the minor versions acts
as the API stability level. This is useful when comparisons of API versions as a
major change is API breaking. For example,
^1.2.3
is equivalent to>= 1.2.3, < 2.0.0
^1.2.x
is equivalent to>= 1.2.0, < 2.0.0
^2.3
is equivalent to>= 2.3, < 3
^2.x
is equivalent to>= 2.0.0, < 3
^0.2.3
is equivalent to>=0.2.3 <0.3.0
^0.2
is equivalent to>=0.2.0 <0.3.0
^0.0.3
is equivalent to>=0.0.3 <0.0.4
^0.0
is equivalent to>=0.0.0 <0.1.0
^0
is equivalent to>=0.0.0 <1.0.0
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
.
set¶
Use set
to add a new key/value pair to a dictionary.
Note that set
returns the dictionary (a requirement of Go template functions),
so you may need to trap the value as done above with the $_
assignmen
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.
shuffle¶
Shuffle a string.
The above will randomize the letters in hello
, perhaps producing oelhl
.
slice¶
To get partial elements of a list, use slice list [n] [m]
. It is
equivalent of list[n:m]
.
slice $myList
returns[1 2 3 4 5]
. It is same asmyList[:]
.slice $myList 3
returns[4 5]
. It is same asmyList[3:]
.slice $myList 1 3
returns[2 3]
. It is same asmyList[1:3]
.slice $myList 0 3
returns[1 2 3]
. It is same asmyList[:3]
.
slice
panics if there is a problem while mustSlice
returns an error to the
template engine if there is a problem.
snakecase¶
Convert string from camelCase to snake_case.
This above will produce first_name
.
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.
split¶
Split a string into a list of strings:
The above will return [foo bar baz]
The older split
function splits a string into a dict
. It is designed to make
it easy to use template dot notation for accessing members:
The above produces a map with index keys. {_0: foo, _1: bar, _2: baz}
The above produces foo
splitList¶
Split a string into a list of strings:
The above will return [foo bar baz]
The older split
function splits a string into a dict
. It is designed to make
it easy to use template dot notation for accessing members:
The above produces a map with index keys. {_0: foo, _1: bar, _2: baz}
The above produces foo
splitn¶
splitn
function splits a string into a dict
. It is designed to make
it easy to use template dot notation for accessing members:
The above produces a map with index keys. {_0: foo, _1: bar$baz}
The above produces foo
squote¶
These functions wrap a string in double quotes (quote
) or single quotes
(squote
).
sub¶
To subtract, use sub
subf¶
Floats version of sub
substr¶
Get a substring from a string. It takes three parameters:
- start (int)
- end (int)
- string (string)
The above returns hello
swapcase¶
Swap the case of a string using a word based algorithm.
Conversion algorithm:
- Upper case character converts to Lower case
- Title case character converts to Lower case
- Lower case character after Whitespace or at start converts to Title case
- Other Lower case character converts to Upper case
- Whitespace is defined by unicode.IsSpace(char)
This above will produce tHIS iS a.tEST
.
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.
or
The above returns "foo"
.
or
The above returns "bar"
.
title¶
Convert to title case:
The above returns Hello World
toDate¶
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".
toDecimal¶
Given a unix octal permission, produce a decimal.
The above converts 0777
to 511
and returns the value as an int64.
toJson¶
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 .Item
.
toPrettyJson¶
The toPrettyJson
function encodes an item into a pretty (indented) JSON string.
The above returns indented JSON string representation of .Item
.
toRawJson¶
The toRawJson
function encodes an item into JSON string with HTML characters unescaped.
The above returns unescaped JSON string representation of .Item
.
toString¶
toString
: Convert to a string.
toStrings¶
Given a list-like collection, produce a slice of strings.
The above converts 1
to "1"
, 2
to "2"
, and so on, and then returns
them as a list.
trim¶
The trim
function removes space from either side of a string:
The above produces hello
trimAll¶
No documentation for this function
trimPrefix¶
Trim just the prefix from a string:
The above returns hello
trimSuffix¶
Trim just the suffix from a string:
The above returns hello
trimall¶
No documentation for this function
trunc¶
Truncate a string (and add no suffix)
The above produces hello
.
The above produces world
.
tuple¶
No documentation for this function
typeIs¶
typeIs
is like kindIs
, but for types: typeIs "*io.Buffer" $myVal
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.
typeIsLike¶
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.
typeOf¶
typeOfreturns the underlying type of a value:
typeOf $foo`
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.
uniq¶
Generate a list with all of the duplicates removed.
The above would produce [1 2]
uniq
panics if there is a problem while mustUniq
returns an error to the
template engine if there is a problem.
unixEpoch¶
Returns the seconds since the unix epoch for a time.Time
.
For more info, check https://golang.org/pkg/net/url/#URL
uuidv4¶
Sprig can generate UUID v4 universally unique IDs.
The above returns a new UUID of the v4 (randomly generated) type.
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 list["value1", "value2", "value 3"]
. Note that the values
function gives no guarantees about the result ordering- if you care about this,
then use sortAlpha
.
without¶
The without
function filters items out of a list.
The above would produce [1 2 4 5]
Without can take more than one filter:
That would produce [2 4]
without
panics if there is a problem while mustWithout
returns an error to the
template engine if there is a problem.
wrap¶
Wrap text at a given column count:
The above will wrap the string in $someText
at 80 columns.
wrapWith¶
wrapWith
works as wrap
, but lets you specify the string to wrap with.
(wrap
uses \n
)
The above produces hello world
(where the whitespace is an ASCII tab
character)