sprout

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 16, 2024 License: MIT Imports: 55 Imported by: 7

README

Sprout Logo

[!NOTE] Sprout is an evolved variant of the Masterminds/sprig library, reimagined for modern Go versions. It introduces fresh functionalities and commits to maintaining the library, picking up where Sprig left off. Notably, Sprig had not seen updates for two years and was not compatible beyond Golang 1.13, necessitating the creation of Sprout.

Motivation

Sprout was born out of the need for a modernized, maintained, and performant template function library. Sprig, the predecessor to Sprout, had not seen updates for two years and was not optimized for later versions of Golang. Sprout aims to fill this gap by providing a library that is actively maintained, compatible with the latest Go versions, and optimized for performance.

Roadmap to Sprout v1.0

You can track our progress towards Sprout v1.0 by following the documentation page here.

Table of Contents

Transitioning from Sprig

Sprout is designed to be a drop-in replacement for Sprig in the v1.0, with the same function names and behavior. To use Sprout in your project, simply replace the Sprig import with Sprout:

import (
-  "github.com/Masterminds/sprig/v3"
+  "github.com/go-sprout/sprout"
)

tpl := template.Must(
  template.New("base").
-   Funcs(sprig.FuncMap()).
+   Funcs(sprout.FuncMap()).
    ParseGlob("*.tmpl")
)

Usage

To use Sprout in your project, import the library and use the FuncMap function to add the template functions to your template:

import (
  "github.com/go-sprout/sprout"
  "text/template"
)

tpl := template.Must(
  template.New("base").
    Funcs(sprout.FuncMap()).
    ParseGlob("*.tmpl")
)

You can customize the behavior of Sprout by creating a FunctionHandler and passing it to the FuncMap function or using the configuration functions provided by Sprout:

handler := sprout.NewFunctionHandler(
  // Add your logger to the handler to log errors and debug information using the
  // standard slog package or any other logger that implements the slog.Logger interface.
  // By default, Sprout uses a slog.TextHandler.
  sprout.WithLogger(slogLogger),
  // Set the error handling behavior for the handler. By default, Sprout returns the default value of the return type without crashes or panics.
  sprout.WithErrHandling(sprout.ErrHandlingReturnDefaultValue),
  // Set the error channel for the handler. By default, Sprout does not use an error channel. If you set an error channel, Sprout will send errors to it.
  // This options is only used when the error handling behavior is set to
  // `ErrHandlingErrorChannel`
  sprout.WithErrorChannel(errChan),
  // Set the alias for a function. By default, Sprout use alias for some functions for backward compatibility with Sprig.
  sprout.WithAlias("hello", "hi"),
)

// Use the handler with the FuncMap function. The handler will be used to handle all template functions.
tpl := template.Must(
  template.New("base").
    Funcs(sprout.FuncMap(sprout.WithFunctionHandler(handler))).
    ParseGlob("*.tmpl")
)

Usage: Logger

Sprout uses the slog package for logging. You can pass your logger to the WithLogger configuration function to log errors and debug information:

// Create a new logger using the slog package.
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))

// Use the handler with the FuncMap function.
tpl := template.Must(
  template.New("base").
    Funcs(sprout.FuncMap(sprout.WithLogger(logger))).
    ParseGlob("*.tmpl")
)

Usage: Alias

Sprout provides the ability to set an alias for a function. This feature is useful for backward compatibility with Sprig. You can set an alias for a function using the WithAlias or WithAliases configuration functions.

See more about the alias in the documentation.

sprout.NewFunctionHandler(
  sprout.WithAlias("hello", "hi"),
)

Usage: Error Handling

Sprout provides three error handling behaviors:

  • ErrHandlingReturnDefaultValue: Sprout returns the default value of the return type without crashes or panics.
  • ErrHandlingPanic: Sprout panics when an error occurs.
  • ErrHandlingErrorChannel: Sprout sends errors to the error channel.

You can set the error handling behavior using the WithErrHandling configuration function:

sprout.NewFunctionHandler(
  sprout.WithErrHandling(sprout.ErrHandlingReturnDefaultValue),
)
Default Value

If you set the error handling behavior to ErrHandlingReturnDefaultValue, Sprout will return the default value of the return type without crashes or panics to ensure a smooth user experience when an error occurs.

Panic

If you set the error handling behavior to ErrHandlingPanic, Sprout will panic when an error occurs to ensure that the error is not ignored and sended back to template execution.

Error Channel

If you set the error handling behavior to ErrHandlingErrorChannel, you can pass an error channel to the WithErrorChannel configuration function. Sprout will send errors to the error channel:

errChan := make(chan error)

sprout.NewFunctionHandler(
  sprout.WithErrHandling(sprout.ErrHandlingErrorChannel),
  sprout.WithErrorChannel(errChan),
)

Performence Benchmarks

To see all the benchmarks, please refer to the benchmarks directory.

Sprig v3.2.3 vs Sprout v0.2

goos: linux
goarch: amd64
pkg: sprout_benchmarks
cpu: Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
BenchmarkSprig-16              1        2152506421 ns/op        44671136 B/op      21938 allocs/op
BenchmarkSprout-16             1        1020721871 ns/op        37916984 B/op      11173 allocs/op
PASS
ok      sprout_benchmarks       3.720s

Time improvement: ((2152506421 - 1020721871) / 2152506421) * 100 = 52.6% Memory improvement: ((44671136 - 37916984) / 44671136) * 100 = 15.1%

So, Sprout v0.3 is approximately 52.6% faster and uses 15.1% less memory than Sprig v3.2.3. 🚀

You can see the full benchmark results here.

Development Philosophy (Currently in reflexion to create our)

Our approach to extending and refining Sprout was guided by several key principles:

  • Empowering layout construction through template functions.
  • Designing template functions that avoid returning errors when possible, instead displaying default values for smoother user experiences.
  • Ensuring template functions operate solely on provided data, without external data fetching.
  • Maintaining the integrity of core Go template functionalities without overrides.

Documentation

Overview

*

  • This file lists the functions originally part of the Sprig library that are
  • intentionally excluded from the Sprout library. The exclusions are based on\
  • community decisions and technical evaluations aimed at enhancing security,
  • relevance, and performance in the context of Go templates.
  • Each exclusion is supported by rational and further community discussions
  • can be found on our GitHub issues page. *
  • Exclusion Criteria:
  • 1. Crypto functions: Deemed inappropriate for Go templates due to inherent security risks.
  • 2. Irrelevant functions: Omitted because they do not provide utility in the context of Go templates.
  • 3. Deprecated/Insecure: Functions using outdated or insecure standards are excluded.
  • 4. Temporary exclusions: Certain functions are temporarily excluded to prevent breaking changes,
  • pending the implementation of the new loader feature.
  • 5. Community decision: Choices made by the community are documented and can be discussed at
  • https://github.com/go-sprout/sprout/issues/1. *
  • The Sprout library is an open-source project and welcomes contributions from the community.
  • To discuss existing exclusions or propose new ones, please contribute to the discussions on
  • our GitHub repository.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FuncMap

func FuncMap(opts ...FunctionHandlerOption) template.FuncMap

FuncMap returns a template.FuncMap for use with text/template or html/template. It provides backward compatibility with sprig.FuncMap and integrates additional configured functions. FOR BACKWARD COMPATIBILITY ONLY

func GenericFuncMap added in v0.4.0

func GenericFuncMap(opts ...FunctionHandlerOption) map[string]interface{}

GenericFuncMap returns a copy of the basic function map as a map[string]interface{}.

func HermeticHtmlFuncMap added in v0.4.0

func HermeticHtmlFuncMap(opts ...FunctionHandlerOption) htemplate.FuncMap

HermeticHtmlFuncMap returns an 'html/template'.Funcmap with only repeatable functions.

func HermeticTxtFuncMap added in v0.4.0

func HermeticTxtFuncMap(opts ...FunctionHandlerOption) ttemplate.FuncMap

HermeticTxtFuncMap returns a 'text/template'.FuncMap with only repeatable functions.

func HtmlFuncMap added in v0.4.0

func HtmlFuncMap(opts ...FunctionHandlerOption) htemplate.FuncMap

HtmlFuncMap returns an 'html/template'.Funcmap

func TxtFuncMap added in v0.4.0

func TxtFuncMap(opts ...FunctionHandlerOption) ttemplate.FuncMap

TxtFuncMap returns a 'text/template'.FuncMap

Types

type DSAKeyFormat

type DSAKeyFormat struct {
	Version       int
	P, Q, G, Y, X *big.Int
}

DSAKeyFormat stores the format for DSA keys. Used by pemBlockForKey

type ErrHandling

type ErrHandling int

ErrHandling defines the strategy for handling errors within FunctionHandler. It supports returning default values, panicking, or sending errors to a specified channel.

const (
	// ErrHandlingReturnDefaultValue indicates that a default value should be
	// returned on error (default).
	ErrHandlingReturnDefaultValue ErrHandling = iota + 1
	// ErrHandlingPanic indicates that a panic should be raised on error.
	ErrHandlingPanic
	// ErrHandlingErrorChannel indicates that errors should be sent to an error
	// channel.
	ErrHandlingErrorChannel
)

type FunctionAliasMap

type FunctionAliasMap map[string][]string

FunctionAliasMap is a map that stores a list of aliases for each function.

type FunctionHandler

type FunctionHandler struct {
	ErrHandling ErrHandling

	Logger *slog.Logger
	// contains filtered or unexported fields
}

FunctionHandler manages function execution with configurable error handling and logging.

func NewFunctionHandler

func NewFunctionHandler(opts ...FunctionHandlerOption) *FunctionHandler

NewFunctionHandler creates a new FunctionHandler with the provided options.

func (*FunctionHandler) Add

func (fh *FunctionHandler) Add(values ...any) any

Add performs addition on a slice of values.

Parameters:

values ...any - numbers to add.

Returns:

any - the sum of the values, converted to the type of the first value.

Example:

{{ 5, 3.5, 2 | add }} // Output: 10.5

func (*FunctionHandler) Add1

func (fh *FunctionHandler) Add1(x any) any

Add performs a unary addition operation on a single value.

Parameters:

x any - the number to add.

Returns:

any - the sum of the value and 1, converted to the type of the input.

Example:

{{ 5 | add1 }} // Output: 6

func (*FunctionHandler) Adler32sum

func (fh *FunctionHandler) Adler32sum(input string) string

func (*FunctionHandler) All

func (fh *FunctionHandler) All(values ...any) bool

All checks if all values in the provided variadic slice are non-empty. It returns true only if none of the values are considered empty by the Empty method.

Parameters:

values ...any - a variadic parameter list of values to be checked.

Returns:

bool - true if all values are non-empty, false otherwise.

Example:

{{ 1, "hello", true | all }} // Output: true
{{ 1, "", true | all }} // Output: false

func (*FunctionHandler) Any

func (fh *FunctionHandler) Any(values ...any) bool

func (*FunctionHandler) Append

func (fh *FunctionHandler) Append(list any, v any) []any

Append adds an element to the end of the list.

Parameters:

list any - the original list to append to.
v any - the element to append.

Returns:

[]any - the new list with the element appended.

Example:

{{ append ["a", "b"], "c" }} // Output: ["a", "b", "c"]

func (*FunctionHandler) Base32Decode

func (fh *FunctionHandler) Base32Decode(s string) string

Base32Decode decodes a Base32 encoded string back to its original form. Returns an error message if the input is not valid Base32.

Parameters:

s string - the Base32 encoded string to decode.

Returns:

string - the decoded string, or an error message if the decoding fails.

Example:

{{ "JBSWY3DPEBLW64TMMQQQ====" | base32Decode }} // Output: "Hello World"

func (*FunctionHandler) Base32Encode

func (fh *FunctionHandler) Base32Encode(s string) string

Base32Encode encodes a string into its Base32 representation.

Parameters:

s string - the string to encode.

Returns:

string - the Base32 encoded string.

Example:

{{ "Hello World" | base32Encode }} // Output: "JBSWY3DPEBLW64TMMQQQ===="

func (*FunctionHandler) Base64Decode

func (fh *FunctionHandler) Base64Decode(s string) string

Base64Decode decodes a Base64 encoded string back to its original form. Returns an error message if the input is not valid Base64.

Parameters:

s string - the Base64 encoded string to decode.

Returns:

string - the decoded string, or an error message if the decoding fails.

Example:

{{ "SGVsbG8gV29ybGQ=" | base64Decode }} // Output: "Hello World"

func (*FunctionHandler) Base64Encode

func (fh *FunctionHandler) Base64Encode(s string) string

Base64Encode encodes a string into its Base64 representation.

Parameters:

s string - the string to encode.

Returns:

string - the Base64 encoded string.

Example:

{{ "Hello World" | base64Encode }} // Output: "SGVsbG8gV29ybGQ="

func (*FunctionHandler) Bcrypt

func (fh *FunctionHandler) Bcrypt(input string) string

func (*FunctionHandler) BuildCustomCertificate

func (fh *FunctionHandler) BuildCustomCertificate(b64cert string, b64key string) (certificate, error)

func (*FunctionHandler) Cat

func (fh *FunctionHandler) Cat(values ...any) string

Cat concatenates a series of values into a single string. Each value is converted to its string representation and separated by a space. Nil values are skipped, and no trailing spaces are added.

Parameters:

values ...any - a variadic parameter list of values to be concatenated.

Returns:

string - a single string composed of all non-nil input values separated
         by spaces.

Example:

{{ "Hello", nil, 123, true | cat }} // Output: "Hello 123 true"

func (*FunctionHandler) Ceil

func (fh *FunctionHandler) Ceil(num any) float64

Ceil returns the smallest integer greater than or equal to the provided number.

Parameters:

num any - the number to ceil, expected to be numeric or convertible to float64.

Returns:

float64 - the ceiled value.

Example:

{{ 3.1 | ceil }} // Output: 4

func (*FunctionHandler) Chunk

func (fh *FunctionHandler) Chunk(size int, list any) [][]any

Chunk divides a list into chunks of specified size.

Parameters:

size int - the size of each chunk.
list any - the list to divide.

Returns:

[][]any - a list of chunks.

Example:

{{ chunk 2, ["a", "b", "c", "d"] }} // Output: [["a", "b"], ["c", "d"]]

func (*FunctionHandler) Coalesce

func (fh *FunctionHandler) Coalesce(values ...any) any

func (*FunctionHandler) Compact

func (fh *FunctionHandler) Compact(list any) []any

Compact removes nil and zero-value elements from a list.

Parameters:

list any - the list to compact.

Returns:

[]any - the list without nil or zero-value elements.

Example:

{{ [0, 1, nil, 2, "", 3] | compact }} // Output: [1, 2, 3]

func (*FunctionHandler) Concat

func (fh *FunctionHandler) Concat(lists ...any) any

Concat merges multiple lists into a single list.

Parameters:

lists ...any - the lists to concatenate.

Returns:

any - a single concatenated list containing elements from all provided lists.

Example:

{{ ["c", "d"] | concat ["a", "b"] }} // Output: ["a", "b", "c", "d"]

func (*FunctionHandler) Contains

func (fh *FunctionHandler) Contains(substring string, str string) bool

Contains checks if 'str' contains the 'substring'.

Parameters:

substring string - the substring to search for.
str string - the string to search within.

Returns:

bool - true if 'str' contains 'substring', false otherwise.

Example:

{{ "Hello" | contains "ell" }} // Output: true

func (*FunctionHandler) Date

func (fh *FunctionHandler) Date(fmt string, date any) string

Date formats a given date or current time into a specified format string.

Parameters:

fmt string - the format string.
date any - the date to format or the current time if not a date type.

Returns:

string - the formatted date.

Example:

{{ "2023-05-04T15:04:05Z" | date "Jan 2, 2006" }} // Output: "May 4, 2023"

func (*FunctionHandler) DateAgo

func (fh *FunctionHandler) DateAgo(date any) string

DateAgo calculates how much time has passed since the given date.

Parameters:

date any - the starting date for the calculation.

Returns:

string - a human-readable string describing how long ago the date was.

Example:

{{ "2023-05-04T15:04:05Z" | dateAgo }} // Output: "4m"

func (*FunctionHandler) DateInZone

func (fh *FunctionHandler) DateInZone(fmt string, date any, zone string) string

DateInZone formats a given date or current time into a specified format string in a specified timezone.

Parameters:

fmt string - the format string.
date any - the date to format, in various acceptable formats.
zone string - the timezone name.

Returns:

string - the formatted date.

Example:

{{ dateInZone "Jan 2, 2006", "2023-05-04T15:04:05Z", "UTC" }} // Output: "May 4, 2023"

func (*FunctionHandler) DateModify

func (fh *FunctionHandler) DateModify(fmt string, date time.Time) time.Time

func (*FunctionHandler) DecryptAES

func (fh *FunctionHandler) DecryptAES(password string, crypt64 string) (string, error)

func (*FunctionHandler) DeepCopy

func (fh *FunctionHandler) DeepCopy(element any) any

DeepCopy performs a deep copy of 'element' and panics if copying fails. It relies on MustDeepCopy to perform the copy and handle errors internally.

Parameters:

element any - the element to be deeply copied.

Returns:

any - a deep copy of 'element'.

Example:

{{ {"name":"John"} | deepCopy }} // Output: {"name":"John"}

func (*FunctionHandler) DeepEqual

func (fh *FunctionHandler) DeepEqual(x, y any) bool

DeepEqual determines if two variables, 'x' and 'y', are deeply equal. It uses reflect.DeepEqual to evaluate equality.

Parameters:

x, y any - the variables to be compared.

Returns:

bool - true if 'x' and 'y' are deeply equal, false otherwise.

Example:

{{ {"a":1}, {"a":1} | deepEqual }} // Output: true

func (*FunctionHandler) Default

func (fh *FunctionHandler) Default(defaultValue any, given ...any) any

Default returns the first non-empty value from the given arguments or a default value if the argument list is empty or the first element is empty. It accepts a default value `defaultValue` of any type and a variadic slice `given` of any type. If `given` is not provided or the first element in `given` is empty, it returns `defaultValue`. Otherwise, it returns the first element of `given`. If you want to catch the first non-empty value from a list of values, use the `Coalesce` function instead.

Parameters:

defaultValue any - the default value to return if no valid argument is
                   provided or if the first argument is empty.
given ...any     - a variadic slice of any type to check the first
                   element of it for emptiness.

Returns:

any - the first element of `given`, or `defaultValue` if `given` is empty
      or all values are empty.

Example:

{{ nil | default "default" }} // Output: "default"
{{ "" | default "default" }}  // Output: "default"
{{ "first" | default "default" }} // Output: "first"
{{ "first" | default "default" "second" }} // Output: "second"

func (*FunctionHandler) DerivePassword

func (fh *FunctionHandler) DerivePassword(counter uint32, passwordType, password, user, site string) string

func (*FunctionHandler) Dict

func (fh *FunctionHandler) Dict(values ...any) map[string]any

Dict creates a dictionary from a list of keys and values.

Parameters:

values ...any - alternating keys and values.

Returns:

map[string]any - the created dictionary.

Example:

{{ dict "key1", "value1", "key2", "value2" }} // Output: {"key1": "value1", "key2": "value2"}

func (*FunctionHandler) Dig

func (fh *FunctionHandler) Dig(args ...any) (any, error)

Dig navigates through a nested dictionary structure using a sequence of keys and returns the value found at the specified path.

Parameters:

args ...any - a sequence of keys followed by a dictionary as the last argument.

Returns:

any - the value found at the nested key path or nil if any key in the path is not found.
error - an error if there are fewer than three arguments, if the last argument is not a dictionary, or if any key is not a string.

Example:

{{ dig "user", "profile", "name", {"user": {"profile": {"name": "John Doe"}}} }} // Output: "John Doe", nil

func (*FunctionHandler) DivInt

func (fh *FunctionHandler) DivInt(values ...any) int64

DivInt divides a sequence of values and returns the result as int64.

Parameters:

values ...any - numbers to divide.

Returns:

int64 - the quotient of the division.

Example:

{{ 30, 3, 2 | divInt }} // Output: 5

func (*FunctionHandler) Divf

func (fh *FunctionHandler) Divf(values ...any) any

Divf divides a sequence of values, starting with the first value, and returns the result.

Parameters:

values ...any - numbers to divide.

Returns:

any - the quotient of the division, converted to the type of the first value.

Example:

{{ 30.0, 3.0, 2.0 | divf }} // Output: 5.0

func (*FunctionHandler) Duration

func (fh *FunctionHandler) Duration(sec any) string

Duration converts seconds into a human-readable duration string.

Parameters:

sec any - the duration in seconds.

Returns:

string - the human-readable duration.

Example:

{{ 3661 | duration }} // Output: "1h1m1s"

func (*FunctionHandler) DurationRound

func (fh *FunctionHandler) DurationRound(duration any) string

DurationRound rounds a duration to the nearest significant unit, such as years or seconds.

Parameters:

duration any - the duration to round.

Returns:

string - the rounded duration.

Example:

{{ "3600s" | durationRound }} // Output: "1h"

func (*FunctionHandler) Ellipsis

func (fh *FunctionHandler) Ellipsis(maxWidth int, str string) string

Ellipsis truncates 'str' to 'maxWidth' and appends an ellipsis if the string is longer than 'maxWidth'.

Parameters:

maxWidth int - the maximum width of the string including the ellipsis.
str string - the string to truncate.

Returns:

string - the possibly truncated string with an ellipsis.

Example:

{{ "Hello World" | ellipsis 10 }} // Output: "Hello W..."

func (*FunctionHandler) EllipsisBoth

func (fh *FunctionHandler) EllipsisBoth(offset int, maxWidth int, str string) string

EllipsisBoth truncates 'str' from both ends, preserving the middle part of the string and appending ellipses to both ends if needed.

Parameters:

offset int - starting position for preserving text.
maxWidth int - the total maximum width including ellipses.
str string - the string to truncate.

Returns:

string - the truncated string with ellipses on both ends.

Example:

{{ "Hello World" | ellipsisBoth 1 10 }} // Output: "...lo Wor..."

func (*FunctionHandler) Empty

func (fh *FunctionHandler) Empty(given any) bool

Empty evaluates the emptiness of the provided value 'given'. It returns true if 'given' is considered empty based on its type. This method is essential for determining the presence or absence of meaningful value across various data types.

Parameters:

given any - the value to be evaluated for emptiness.

Returns:

bool - true if 'given' is empty, false otherwise.

This method utilizes the reflect package to inspect the type and value of 'given'. Depending on the type, it checks for nil pointers, zero-length collections (arrays, slices, maps, and strings), zero values of numeric types (integers, floats, complex numbers, unsigned ints), and false for booleans.

Example:

{{ nil | empty }} // Output: true
{{ "" | empty }} // Output: true
{{ 0 | empty }} // Output: true
{{ false | empty }} // Output: true
{{ struct{}{} | empty }} // Output: false

func (*FunctionHandler) EncryptAES

func (fh *FunctionHandler) EncryptAES(password string, plaintext string) (string, error)

func (*FunctionHandler) Env

func (fh *FunctionHandler) Env(key string) string

Env retrieves the value of an environment variable.

Parameters:

key string - the name of the environment variable.

Returns:

string - the value of the environment variable.

Example:

{{ "PATH" | env }} // Output: "/usr/bin:/bin:/usr/sbin:/sbin"

func (*FunctionHandler) ExpandEnv

func (fh *FunctionHandler) ExpandEnv(str string) string

ExpandEnv replaces ${var} or $var in the string based on the values of the current environment variables.

Parameters:

str string - the string with environment variables to expand.

Returns:

string - the expanded string.

Example:

{{ "Path is $PATH" | expandEnv }} // Output: "Path is /usr/bin:/bin:/usr/sbin:/sbin"

func (*FunctionHandler) Fail

func (fh *FunctionHandler) Fail(message string) (*uint, error)

! DEPRECATED: This should be removed in the next major version.

Fail creates an error with a specified message and returns a nil pointer alongside the created error. This function is typically used to indicate failure conditions in functions that return a pointer and an error.

Parameters:

message string - the error message to be associated with the returned error.

Returns:

*uint - always returns nil, indicating no value is associated with the failure.
error - the error object containing the provided message.

Example:

{{ "Operation failed" | fail }} // Output: nil, error with "Operation failed"

func (*FunctionHandler) First

func (fh *FunctionHandler) First(list any) any

First returns the first element of a list.

Parameters:

list any - the list from which to take the first element.

Returns:

any - the first element of the list.

Example:

{{ [1, 2, 3, 4] | first }} // Output: 1

func (*FunctionHandler) Floor

func (fh *FunctionHandler) Floor(num any) float64

Floor returns the largest integer less than or equal to the provided number.

Parameters:

num any - the number to floor, expected to be numeric or convertible to float64.

Returns:

float64 - the floored value.

Example:

{{ 3.7 | floor }} // Output: 3

func (*FunctionHandler) FromJson

func (fh *FunctionHandler) FromJson(v string) any

FromJson converts a JSON string into a corresponding Go data structure.

Parameters:

v string - the JSON string to decode.

Returns:

any - the decoded Go data structure, or nil if the decoding fails.

Example:

result := fh.FromJson(`{"name":"John", "age":30}`)
fmt.Printf("%v\n", result) // Output: map[name:John age:30]

func (*FunctionHandler) FromYAML added in v0.4.0

func (fh *FunctionHandler) FromYAML(str string) any

FromYAML deserializes a YAML string into a Go map.

Parameters:

str string - the YAML string to deserialize.

Returns:

any - a map representing the YAML data. Returns nil if deserialization fails.

Example:

{{ "name: John Doe\nage: 30" | fromYAML }} // Output: map[name:John Doe age:30]

func (*FunctionHandler) GenerateCertificateAuthority

func (fh *FunctionHandler) GenerateCertificateAuthority(
	cn string,
	daysValid int,
) (certificate, error)

func (*FunctionHandler) GenerateCertificateAuthorityWithKeyInternal

func (fh *FunctionHandler) GenerateCertificateAuthorityWithKeyInternal(
	cn string,
	daysValid int,
	priv crypto.PrivateKey,
) (certificate, error)

func (*FunctionHandler) GenerateCertificateAuthorityWithPEMKey

func (fh *FunctionHandler) GenerateCertificateAuthorityWithPEMKey(
	cn string,
	daysValid int,
	privPEM string,
) (certificate, error)

func (*FunctionHandler) GeneratePrivateKey

func (fh *FunctionHandler) GeneratePrivateKey(typ string) string

func (*FunctionHandler) GenerateSelfSignedCertificate

func (fh *FunctionHandler) GenerateSelfSignedCertificate(
	cn string,
	ips []interface{},
	alternateDNS []interface{},
	daysValid int,
) (certificate, error)

func (*FunctionHandler) GenerateSelfSignedCertificateWithKeyInternal

func (fh *FunctionHandler) GenerateSelfSignedCertificateWithKeyInternal(
	cn string,
	ips []interface{},
	alternateDNS []interface{},
	daysValid int,
	priv crypto.PrivateKey,
) (certificate, error)

func (*FunctionHandler) GenerateSelfSignedCertificateWithPEMKey

func (fh *FunctionHandler) GenerateSelfSignedCertificateWithPEMKey(
	cn string,
	ips []interface{},
	alternateDNS []interface{},
	daysValid int,
	privPEM string,
) (certificate, error)

func (*FunctionHandler) GenerateSignedCertificate

func (fh *FunctionHandler) GenerateSignedCertificate(
	cn string,
	ips []interface{},
	alternateDNS []interface{},
	daysValid int,
	ca certificate,
) (certificate, error)

func (*FunctionHandler) GenerateSignedCertificateWithKeyInternal

func (fh *FunctionHandler) GenerateSignedCertificateWithKeyInternal(
	cn string,
	ips []interface{},
	alternateDNS []interface{},
	daysValid int,
	ca certificate,
	priv crypto.PrivateKey,
) (certificate, error)

func (*FunctionHandler) GenerateSignedCertificateWithPEMKey

func (fh *FunctionHandler) GenerateSignedCertificateWithPEMKey(
	cn string,
	ips []interface{},
	alternateDNS []interface{},
	daysValid int,
	ca certificate,
	privPEM string,
) (certificate, error)

func (*FunctionHandler) Get

func (fh *FunctionHandler) Get(dict map[string]any, key string) any

Get retrieves the value associated with the specified key from the dictionary.

Parameters:

dict map[string]any - the dictionary.
key string - the key to look up.

Returns:

any - the value associated with the key, or an empty string if the key does not exist.

Example:

{{ get {"key": "value"}, "key" }} // Output: "value"

func (*FunctionHandler) GetAlternateDNSStrs

func (fh *FunctionHandler) GetAlternateDNSStrs(alternateDNS []interface{}) ([]string, error)

func (*FunctionHandler) GetBaseCertTemplate

func (fh *FunctionHandler) GetBaseCertTemplate(
	cn string,
	ips []interface{},
	alternateDNS []interface{},
	daysValid int,
) (*x509.Certificate, error)

func (*FunctionHandler) GetCertAndKey

func (fh *FunctionHandler) GetCertAndKey(
	template *x509.Certificate,
	signeeKey crypto.PrivateKey,
	parent *x509.Certificate,
	signingKey crypto.PrivateKey,
) (string, string, error)

func (*FunctionHandler) GetHostByName

func (fh *FunctionHandler) GetHostByName(name string) string

func (*FunctionHandler) GetNetIPs

func (fh *FunctionHandler) GetNetIPs(ips []interface{}) ([]net.IP, error)

func (*FunctionHandler) GetPublicKey

func (fh *FunctionHandler) GetPublicKey(priv crypto.PrivateKey) (crypto.PublicKey, error)

func (*FunctionHandler) Has

func (fh *FunctionHandler) Has(element any, list any) bool

Has checks if the specified element is present in the collection.

Parameters:

element any - the element to search for.
list any - the collection to search.

Returns:

bool - true if the element is found, otherwise false.

Example:

{{ ["value", "other"] | has "value" }} // Output: true

func (*FunctionHandler) HasKey

func (fh *FunctionHandler) HasKey(dict map[string]any, key string) bool

HasKey checks if the specified key exists in the dictionary.

Parameters:

dict map[string]any - the dictionary to check.
key string - the key to look for.

Returns:

bool - true if the key exists, otherwise false.

Example:

{{ hasKey {"key": "value"}, "key" }} // Output: true

func (*FunctionHandler) HasPrefix

func (fh *FunctionHandler) HasPrefix(prefix string, str string) bool

HasPrefix checks if 'str' starts with the specified 'prefix'.

Parameters:

prefix string - the prefix to check.
str string - the string to check.

Returns:

bool - true if 'str' starts with 'prefix', false otherwise.

Example:

{{ "HelloWorld" | hasPrefix "Hello" }} // Output: true

func (*FunctionHandler) HasSuffix

func (fh *FunctionHandler) HasSuffix(suffix string, str string) bool

HasSuffix checks if 'str' ends with the specified 'suffix'.

Parameters:

suffix string - the suffix to check.
str string - the string to check.

Returns:

bool - true if 'str' ends with 'suffix', false otherwise.

Example:

{{ "HelloWorld" | hasSuffix "World" }} // Output: true

func (*FunctionHandler) Hello

func (fh *FunctionHandler) Hello() string

Hello returns a greeting string. It simply returns the string "Hello!" to be used as a test function.

func (*FunctionHandler) HtmlDate

func (fh *FunctionHandler) HtmlDate(date any) string

HtmlDate formats a date into a standard HTML date format (YYYY-MM-DD).

Parameters:

date any - the date to format.

Returns:

string - the formatted date in HTML format.

Example:

{{ "2023-05-04T15:04:05Z" | htmlDate }} // Output: "2023-05-04"

func (*FunctionHandler) HtmlDateInZone

func (fh *FunctionHandler) HtmlDateInZone(date any, zone string) string

HtmlDateInZone formats a date into a standard HTML date format (YYYY-MM-DD) in a specified timezone.

Parameters:

date any - the date to format.
zone string - the timezone name.

Returns:

string - the formatted date in HTML format.

Example:

{{ "2023-05-04T15:04:05Z", "UTC" | htmlDateInZone }} // Output: "2023-05-04"

func (*FunctionHandler) Htpasswd

func (fh *FunctionHandler) Htpasswd(username string, password string) string

func (*FunctionHandler) InList

func (fh *FunctionHandler) InList(haystack []any, needle any) bool

func (*FunctionHandler) Indent

func (fh *FunctionHandler) Indent(spaces int, str string) string

Indent adds spaces to the beginning of each line in 'str'.

Parameters:

spaces int - the number of spaces to add.
str string - the string to indent.

Returns:

string - the indented string.

Example:

{{ "Hello\nWorld" | indent 4 }} // Output: "    Hello\n    World"

func (*FunctionHandler) Initial

func (fh *FunctionHandler) Initial(list any) []any

Initial returns all elements of a list except the last.

Parameters:

list any - the list to process.

Returns:

[]any - the list without the last element.

Example:

{{ [1, 2, 3, 4] | initial }} // Output: [1, 2, 3]

func (*FunctionHandler) Initials

func (fh *FunctionHandler) Initials(str string) string

Initials extracts the initials from 'str', using optional 'delimiters' to determine word boundaries.

Parameters:

str string - the string from which to extract initials.
delimiters string - optional string containing delimiter characters.

Returns:

string - the initials of the words in 'str'.

Example:

{{ "John Doe" | initials }} // Output: "JD"

func (*FunctionHandler) Join

func (fh *FunctionHandler) Join(sep string, v any) string

Join concatenates the elements of a slice into a single string separated by 'sep'. The slice is extracted from 'v', which can be any slice input. The function uses 'Strslice' to convert 'v' to a slice of strings if necessary.

Parameters:

sep string - the separator string.
v any - the slice to join, can be of any slice type.

Returns:

string - the concatenated string.

Example:

{{ $list := slice "apple" "banana" "cherry" }}
{{ $list | join ", " }} // Output: "apple, banana, cherry"

func (*FunctionHandler) Keys

func (fh *FunctionHandler) Keys(dicts ...map[string]any) []string

Keys retrieves all keys from one or more dictionaries.

Parameters:

dicts ...map[string]any - one or more dictionaries.

Returns:

[]string - a list of all keys from the dictionaries.

Example:

{{ keys {"key1": "value1", "key2": "value2"} }} // Output: ["key1", "key2"]

func (*FunctionHandler) KindIs

func (fh *FunctionHandler) KindIs(target string, src any) bool

KindIs compares the kind of 'src' to a target kind string 'target'. It returns true if the kind of 'src' matches the 'target'.

Parameters:

target string - the string representation of the kind to check against.
src any - the variable whose kind is being checked.

Returns:

bool - true if 'src's kind is 'target', false otherwise.

Example:

{{ "int", 42 | kindIs }} // Output: true

func (*FunctionHandler) KindOf

func (fh *FunctionHandler) KindOf(src any) string

KindOf returns the kind of 'src' as a string.

Parameters:

src any - the variable whose kind is being determined.

Returns:

string - the string representation of 'src's kind.

Example:

{{ 42 | kindOf }} // Output: "int"

func (*FunctionHandler) Last

func (fh *FunctionHandler) Last(list any) any

Last returns the last element of a list.

Parameters:

list any - the list from which to take the last element.

Returns:

any - the last element of the list.

Example:

{{ [1, 2, 3, 4] | last }} // Output: 4

func (*FunctionHandler) List

func (fh *FunctionHandler) List(values ...any) []any

List creates a list from the provided elements.

Parameters:

values ...any - the elements to include in the list.

Returns:

[]any - the created list containing the provided elements.

Example:

{{ 1, 2, 3 | list }} // Output: [1, 2, 3]

func (*FunctionHandler) Max

func (fh *FunctionHandler) Max(a any, i ...any) int64

Max returns the maximum value among the provided arguments.

Parameters:

a any - the first number to compare.
i ...any - additional numbers to compare.

Returns:

int64 - the largest number among the inputs.

Example:

{{ 5, 3, 8, 2 | max }} // Output: 8

func (*FunctionHandler) Maxf

func (fh *FunctionHandler) Maxf(a any, i ...any) float64

Maxf returns the maximum value among the provided floating-point arguments.

Parameters:

a any - the first number to compare, expected to be numeric or convertible to float64.
i ...any - additional numbers to compare.

Returns:

float64 - the largest number among the inputs.

Example:

{{ 5.2, 3.8, 8.1, 2.6 | maxf }} // Output: 8.1

func (*FunctionHandler) Merge

func (fh *FunctionHandler) Merge(dest map[string]any, srcs ...map[string]any) any

Merge combines multiple source maps into a destination map without overwriting existing keys.

Parameters:

dest map[string]any - the destination map.
srcs ...map[string]any - one or more source maps to merge into the destination.

Returns:

any - the merged destination map.

Example:

{{ merge {}, {"a": 1}, {"b": 2} }} // Output: {"a": 1, "b": 2}

func (*FunctionHandler) MergeOverwrite

func (fh *FunctionHandler) MergeOverwrite(dest map[string]any, srcs ...map[string]any) any

MergeOverwrite combines multiple source maps into a destination map, overwriting existing keys.

Parameters:

dest map[string]any - the destination map.
srcs ...map[string]any - one or more source maps to merge into the destination, with overwriting.

Returns:

any - the merged destination map with overwritten values where applicable.

Example:

{{ mergeOverwrite {}, {"a": 1}, {"a": 2, "b": 3} }} // Output: {"a": 2, "b": 3}

func (*FunctionHandler) Min

func (fh *FunctionHandler) Min(a any, i ...any) int64

Min returns the minimum value among the provided arguments.

Parameters:

a any - the first number to compare.
i ...any - additional numbers to compare.

Returns:

int64 - the smallest number among the inputs.

Example:

{{ 5, 3, 8, 2 | min }} // Output: 2

func (*FunctionHandler) Minf

func (fh *FunctionHandler) Minf(a any, i ...any) float64

Minf returns the minimum value among the provided floating-point arguments.

Parameters:

a any - the first number to compare, expected to be numeric or convertible to float64.
i ...any - additional numbers to compare.

Returns:

float64 - the smallest number among the inputs.

Example:

{{ 5.2, 3.8, 8.1, 2.6 | minf }} // Output: 2.6

func (*FunctionHandler) Mod

func (fh *FunctionHandler) Mod(x, y any) any

Mod returns the remainder of division of 'x' by 'y'.

Parameters:

x any, y any - numbers to divide, expected to be numeric or convertible to float64.

Returns:

any - the remainder, converted to the type of 'x'.

Example:

{{ 10, 4 | mod }} // Output: 2

func (*FunctionHandler) MulInt

func (fh *FunctionHandler) MulInt(values ...any) int64

MulInt multiplies a sequence of values and returns the result as int64.

Parameters:

values ...any - numbers to multiply, expected to be numeric or convertible to float64.

Returns:

int64 - the product of the values.

Example:

{{ 5, 3, 2 | mulInt }} // Output: 30

func (*FunctionHandler) Mulf

func (fh *FunctionHandler) Mulf(values ...any) any

Mulf multiplies a sequence of values and returns the result as float64.

Parameters:

values ...any - numbers to multiply.

Returns:

any - the product of the values, converted to the type of the first value.

Example:

{{ 5.5, 2.0, 2.0 | mulf }} // Output: 22.0

func (*FunctionHandler) MustAppend

func (fh *FunctionHandler) MustAppend(list any, v any) ([]any, error)

MustAppend appends an element to a slice or array, returning an error if the operation isn't applicable.

Parameters:

list any - the original list to append to.
v any - the element to append.

Returns:

[]any - the new list with the element appended.
error - error if the list is nil or not a slice/array.

Example:

{{ mustAppend ["a", "b"], "c"  }} // Output: ["a", "b", "c"], nil

func (*FunctionHandler) MustChunk

func (fh *FunctionHandler) MustChunk(size int, list any) ([][]any, error)

MustChunk divides a list into chunks of specified size, returning an error if the list is nil or not a slice/array.

Parameters:

size int - the maximum size of each chunk.
list any - the list to chunk.

Returns:

[][]any - a list of chunks.
error - error if the list is nil or not a slice/array.

Example:

{{ ["a", "b", "c", "d"] | mustChunk 2 }} // Output: [["a", "b"], ["c", "d"]], nil

func (*FunctionHandler) MustCompact

func (fh *FunctionHandler) MustCompact(list any) ([]any, error)

MustCompact removes nil or zero-value elements from a list.

Parameters:

list any - the list to compact.

Returns:

[]any - the list without nil or zero-value elements.
error - error if the list is nil or not a slice/array.

Example:

{{ [0, 1, nil, 2, "", 3] | mustCompact }} // Output: [1, 2, 3], nil

func (*FunctionHandler) MustDateModify

func (fh *FunctionHandler) MustDateModify(fmt string, date time.Time) (time.Time, error)

MustDateModify calculates a new date by adding a specified duration to a given date. It returns an error if the duration format is incorrect.

Parameters:

fmt string - the duration string to be added to the date (e.g., "2h", "1m30s").
date time.Time - the initial date to which the duration is added.

Returns:

time.Time - the modified date after adding the duration.
error - error if the duration format is invalid.

Example:

{{ "2024-05-04T15:04:05Z" | mustDateModify "48h" }} // Output: "2024-05-06T15:04:05Z", nil

func (*FunctionHandler) MustDeepCopy

func (fh *FunctionHandler) MustDeepCopy(element any) (any, error)

func (*FunctionHandler) MustFirst

func (fh *FunctionHandler) MustFirst(list any) (any, error)

MustFirst returns the first element of a list.

Parameters:

list any - the list from which to take the first element.

Returns:

any - the first element of the list.
error - error if the list is nil, empty, or not a slice/array.

Example:

{{ [1, 2, 3, 4] | mustFirst }} // Output: 1, nil

func (*FunctionHandler) MustFromJson

func (fh *FunctionHandler) MustFromJson(v string) (any, error)

MustFromJson decodes a JSON string into a Go data structure, returning an error if decoding fails.

Parameters:

v string - the JSON string to decode.

Returns:

any - the decoded Go data structure.
error - error encountered during decoding, if any.

Example:

{{ `{"name":"John", "age":30}` | mustFromJson }} // Output: map[name:John age:30], nil

func (*FunctionHandler) MustFromYAML added in v0.4.0

func (fh *FunctionHandler) MustFromYAML(v string) (any, error)

MustFromYaml deserializes a YAML string into a Go data structure, returning the result along with any error that occurs.

Parameters:

v string - the YAML string to deserialize.

Returns:

any - the Go data structure representing the deserialized YAML content.
error - an error if the YAML content cannot be deserialized.

Example:

{{ "name: John Doe\nage: 30" | mustFromYaml }} // Output: map[name:John Doe age:30], nil

func (*FunctionHandler) MustHas

func (fh *FunctionHandler) MustHas(element any, list any) (bool, error)

MustHas checks if a specified element is present in a collection and handles type errors.

Parameters:

element any - the element to search for in the collection.
list any - the collection in which to search for the element.

Returns:

bool - true if the element is found, otherwise false.
error - error if the list is not a type that can be searched (not a slice or array).

Example:

{{ [1, 2, 3, 4] | mustHas 3 }} // Output: true, nil

func (*FunctionHandler) MustInitial

func (fh *FunctionHandler) MustInitial(list any) ([]any, error)

MustInitial returns all elements of a list except the last.

Parameters:

list any - the list to process.

Returns:

[]any - the list without the last element.
error - error if the list is nil or not a slice/array.

Example:

{{ [1, 2, 3, 4] | mustInitial }} // Output: [1, 2, 3], nil

func (*FunctionHandler) MustLast

func (fh *FunctionHandler) MustLast(list any) (any, error)

MustLast returns the last element of a list.

Parameters:

list any - the list from which to take the last element.

Returns:

any - the last element of the list.
error - error if the list is nil, empty, or not a slice/array.

Example:

{{ [1, 2, 3, 4] | mustLast }} // Output: 4, nil

func (*FunctionHandler) MustMerge

func (fh *FunctionHandler) MustMerge(dest map[string]any, srcs ...map[string]any) (any, error)

MustMerge merges multiple source maps into a destination map without overwriting existing keys in the destination. If an error occurs during merging, it returns nil and the error.

Parameters:

dest map[string]any - the destination map to which all source map key-values are added.
srcs ...map[string]any - one or more source maps whose key-values are added to the destination.

Returns:

any - the merged destination map.
error - error if the merge fails.

Example:

{{ mustMerge {}, {"a": 1, "b": 2}, {"b": 3, "c": 4}  }} // Output: {"a": 1, "b": 2, "c": 4}, nil

func (*FunctionHandler) MustMergeOverwrite

func (fh *FunctionHandler) MustMergeOverwrite(dest map[string]any, srcs ...map[string]any) (any, error)

MustMergeOverwrite merges multiple source maps into a destination map, overwriting existing keys in the destination. If an error occurs during merging, it returns nil and the error.

Parameters:

dest map[string]any - the destination map to which all source map key-values are added.
srcs ...map[string]any - one or more source maps whose key-values are added to the destination, potentially overwriting existing keys.

Returns:

any - the merged destination map with overwritten values where applicable.
error - error if the merge fails.

Example:

{{ mustMergeOverwrite {}, {"a": 1, "b": 2}, {"b": 3, "c": 4} }} // Output: {"a": 1, "b": 3, "c": 4}, nil

func (*FunctionHandler) MustPrepend

func (fh *FunctionHandler) MustPrepend(list any, v any) ([]any, error)

MustPrepend prepends an element to a slice or array, returning an error if the operation isn't applicable.

Parameters:

list any - the original list to prepend to.
v any - the element to prepend.

Returns:

[]any - the new list with the element prepended.
error - error if the list is nil or not a slice/array.

Example:

{{ mustPrepend ["b", "c"], "a" }} // Output: ["a", "b", "c"], nil

func (*FunctionHandler) MustRegexFind

func (fh *FunctionHandler) MustRegexFind(regex string, s string) (string, error)

MustRegexFind searches for the first match of a regex pattern in a string and returns it, with error handling.

Parameters:

regex string - the regular expression to search with.
s string - the string to search within.

Returns:

string - the first regex match found.
error - error if the regex fails to compile.

Example:

{{ "hello world" | mustRegexFind "hello" }} // Output: "hello", nil

func (*FunctionHandler) MustRegexFindAll

func (fh *FunctionHandler) MustRegexFindAll(regex string, s string, n int) ([]string, error)

MustRegexFindAll finds all matches of a regex pattern in a string up to a specified limit, with error handling.

Parameters:

regex string - the regular expression to search with.
s string - the string to search within.
n int - the maximum number of matches to return; use -1 for no limit.

Returns:

[]string - all regex matches found.
error - error if the regex fails to compile.

Example:

{{ mustRegexFindAll "a.", "aba acada afa", 3 }} // Output: ["ab", "ac", "af"], nil

func (*FunctionHandler) MustRegexMatch

func (fh *FunctionHandler) MustRegexMatch(regex string, s string) (bool, error)

MustRegexMatch checks if a string matches a regex pattern, with error handling.

Parameters:

regex string - the regular expression to match against.
s string - the string to check.

Returns:

bool - true if the string matches the regex pattern, otherwise false.
error - error if the regex fails to compile.

Example:

{{ mustRegexMatch "^[a-zA-Z]+$", "Hello" }} // Output: true, nil

func (*FunctionHandler) MustRegexReplaceAll

func (fh *FunctionHandler) MustRegexReplaceAll(regex string, s string, repl string) (string, error)

MustRegexReplaceAll replaces all occurrences of a regex pattern in a string with a replacement string, with error handling.

Parameters:

regex string - the regular expression to replace.
s string - the string containing the original text.
repl string - the replacement text.

Returns:

string - the modified string after all replacements.
error - error if the regex fails to compile.

Example:

{{ mustRegexReplaceAll "\\d", "R2D2 C3PO", "X" }} // Output: "RXDX CXPO", nil

func (*FunctionHandler) MustRegexReplaceAllLiteral

func (fh *FunctionHandler) MustRegexReplaceAllLiteral(regex string, s string, repl string) (string, error)

MustRegexReplaceAllLiteral replaces all occurrences of a regex pattern in a string with a literal replacement string, with error handling.

Parameters:

regex string - the regular expression to replace.
s string - the string containing the original text.
repl string - the literal replacement text.

Returns:

string - the modified string after all replacements, treating the replacement text as literal text.
error - error if the regex fails to compile.

Example:

{{ mustRegexReplaceAllLiteral "world", "hello world", "$1" }} // Output: "hello $1", nil

func (*FunctionHandler) MustRegexSplit

func (fh *FunctionHandler) MustRegexSplit(regex string, s string, n int) ([]string, error)

MustRegexSplit splits a string by a regex pattern up to a specified number of substrings, with error handling.

Parameters:

regex string - the regular expression to split by.
s string - the string to split.
n int - the maximum number of substrings to return; use -1 for no limit.

Returns:

[]string - the substrings resulting from the split.
error - error if the regex fails to compile.

Example:

{{ mustRegexSplit "\\s+", "hello world from Go", 2 }} // Output: ["hello", "world from Go"], nil

func (*FunctionHandler) MustRest

func (fh *FunctionHandler) MustRest(list any) ([]any, error)

MustRest returns all elements of a list except the first.

Parameters:

list any - the list to process.

Returns:

[]any - the list without the first element.
error - error if the list is nil or not a slice/array.

Example:

{{ [1, 2, 3, 4] | mustRest }} // Output: [2, 3, 4], nil

func (*FunctionHandler) MustReverse

func (fh *FunctionHandler) MustReverse(list any) ([]any, error)

MustReverse returns a new list with the elements in reverse order.

Parameters:

list any - the list to reverse.

Returns:

[]any - the list in reverse order.
error - error if the list is nil or not a slice/array.

Example:

{{ [1, 2, 3, 4] | mustReverse }} // Output: [4, 3, 2, 1], nil

func (*FunctionHandler) MustSlice

func (fh *FunctionHandler) MustSlice(list any, indices ...any) (any, error)

MustSlice extracts a slice from a list between two indices.

Parameters:

list any - the list to slice.
indices ...any - the start and optional end indices; if end is omitted,

slices to the end.

Returns:

any - the sliced part of the list.
error - error if the list is nil or not a slice/array.

Example:

{{ mustSlice [1, 2, 3, 4, 5], 1, 3 }} // Output: [2, 3], nil

func (*FunctionHandler) MustToDate

func (fh *FunctionHandler) MustToDate(fmt, str string) (time.Time, error)

MustToDate tries to parse a string into a time.Time object based on a format, returning an error if parsing fails.

Parameters:

fmt string - the date format string.
str string - the date string to parse.

Returns:

time.Time - the parsed date.
error - error if the date string does not conform to the format.

Example:

{{ "2006-01-02", "2023-05-04" | mustToDate }} // Output: 2023-05-04 00:00:00 +0000 UTC, nil

func (*FunctionHandler) MustToJson

func (fh *FunctionHandler) MustToJson(v any) (string, error)

MustToJson encodes a Go data structure into a JSON string, returning an error if encoding fails.

Parameters:

v any - the Go data structure to encode.

Returns:

string - the JSON-encoded string.
error - error encountered during encoding, if any.

Example:

{{ {"name": "John", "age": 30} | mustToJson }} // Output: "{"age":30,"name":"John"}", nil

func (*FunctionHandler) MustToPrettyJson

func (fh *FunctionHandler) MustToPrettyJson(v any) (string, error)

MustToPrettyJson encodes a Go data structure into a pretty-printed JSON string, returning an error if encoding fails.

Parameters:

v any - the Go data structure to encode.

Returns:

string - the pretty-printed JSON string.
error - error encountered during encoding, if any.

Example:

{{ {"name": "John", "age": 30} | mustToPrettyJson }} // Output: "{\n  \"age\": 30,\n  \"name\": \"John\"\n}", nil

func (*FunctionHandler) MustToRawJson

func (fh *FunctionHandler) MustToRawJson(v any) (string, error)

MustToRawJson encodes a Go data structure into a JSON string without escaping HTML, returning an error if encoding fails.

Parameters:

v any - the Go data structure to encode.

Returns:

string - the raw JSON string.
error - error encountered during encoding, if any.

Example:

{{ {"content": "<div>Hello World!</div>"} | mustToRawJson }} // Output: "{\"content\":\"<div>Hello World!</div>\"}", nil

func (*FunctionHandler) MustToYAML added in v0.4.0

func (fh *FunctionHandler) MustToYAML(v any) (string, error)

MustToYAML serializes a Go data structure to a YAML string and returns any error that occurs during the serialization.

Parameters:

v any - the data structure to serialize.

Returns:

string - the YAML string representation of the data structure.
error - error if the serialization fails.

Example:

{{ {"name": "John Doe", "age": 30} | mustToYAML }} // Output: "name: John Doe\nage: 30\n", nil

func (*FunctionHandler) MustUniq

func (fh *FunctionHandler) MustUniq(list any) ([]any, error)

MustUniq returns a new slice containing unique elements of the given list, preserving order.

Parameters:

list any - the list from which to remove duplicates.

Returns:

[]any - a list containing only the unique elements.
error - error if the list is nil or not a slice/array.

Example:

{{ ["a", "b", "a", "c"] | mustUniq }} // Output: ["a", "b", "c"], nil

func (*FunctionHandler) MustWithout

func (fh *FunctionHandler) MustWithout(list any, omit ...any) ([]any, error)

MustWithout returns a new list excluding specified elements.

Parameters:

list any - the original list.
omit ...any - elements to exclude from the new list.

Returns:

[]any - the list excluding the specified elements.
error - error if the list is nil or not a slice/array.

Example:

{{ mustWithout [1, 2, 3, 4], 2, 4 }} // Output: [1, 3], nil

func (*FunctionHandler) Nindent

func (fh *FunctionHandler) Nindent(spaces int, str string) string

func (*FunctionHandler) Nospace

func (fh *FunctionHandler) Nospace(str string) string

Nospace removes all whitespace characters from the provided string. It uses the unicode package to identify whitespace runes and removes them.

Parameters:

str string - the string from which to remove whitespace.

Returns:

string - the modified string with all whitespace characters removed.

Example:

{{ "Hello World" | nospace }} // Output: "HelloWorld"

func (*FunctionHandler) Now

func (fh *FunctionHandler) Now() time.Time

Now returns the current time.

Returns:

time.Time - the current time.

Example:

{{ now }} // Output: "2023-05-07T15:04:05Z"

func (*FunctionHandler) Omit

func (fh *FunctionHandler) Omit(dict map[string]any, keys ...string) map[string]any

Omit creates a new dictionary by excluding specified keys from the original dictionary.

Parameters:

dict map[string]any - the source dictionary.
keys ...string - the keys to exclude from the new dictionary.

Returns:

map[string]any - a dictionary without the omitted keys.

Example:

{{ omit {"key1": "value1", "key2": "value2", "key3": "value3"}, "key2" }} // Output: {"key1": "value1", "key3": "value3"}

func (*FunctionHandler) OsBase

func (fh *FunctionHandler) OsBase(str string) string

OsBase returns the last element of the path, using the OS-specific path separator.

Parameters:

str string - the path string.

Returns:

string - the base element of the path.

Example:

{{ "C:\\path\\to\\file.txt" | osBase }} // Output: "file.txt"

func (*FunctionHandler) OsClean

func (fh *FunctionHandler) OsClean(str string) string

OsClean cleans up the path, using the OS-specific path separator and simplifying redundancies.

Parameters:

str string - the path string.

Returns:

string - the cleaned path.

Example:

{{ "C:\\path\\\\to\\file.txt" | osClean }} // Output: "C:\\path\\to\\file.txt"

func (*FunctionHandler) OsDir

func (fh *FunctionHandler) OsDir(str string) string

OsDir returns all but the last element of the path, using the OS-specific path separator.

Parameters:

str string - the path string.

Returns:

string - the directory part of the path.

Example:

{{ "C:\\path\\to\\file.txt" | osDir }} // Output: "C:\\path\\to"

func (*FunctionHandler) OsExt

func (fh *FunctionHandler) OsExt(str string) string

OsExt returns the file extension of the path, using the OS-specific path separator.

Parameters:

str string - the path string.

Returns:

string - the extension of the file in the path.

Example:

{{ "C:\\path\\to\\file.txt" | osExt }} // Output: ".txt"

func (*FunctionHandler) OsIsAbs

func (fh *FunctionHandler) OsIsAbs(str string) bool

OsIsAbs checks if the path is absolute, using the OS-specific path separator.

Parameters:

str string - the path string.

Returns:

bool - true if the path is absolute, otherwise false.

Example:

{{ "C:\\path\\to\\file.txt" | osIsAbs }} // Output: true

func (*FunctionHandler) ParsePrivateKeyPEM

func (fh *FunctionHandler) ParsePrivateKeyPEM(pemBlock string) (crypto.PrivateKey, error)

func (*FunctionHandler) PathBase

func (fh *FunctionHandler) PathBase(str string) string

PathBase returns the last element of the path.

Parameters:

str string - the path string.

Returns:

string - the base element of the path.

Example:

{{ "/path/to/file.txt" | pathBase }} // Output: "file.txt"

func (*FunctionHandler) PathClean

func (fh *FunctionHandler) PathClean(str string) string

PathClean cleans up the path, simplifying any redundancies like double slashes.

Parameters:

str string - the path string.

Returns:

string - the cleaned path.

Example:

{{ "/path//to/file.txt" | pathClean }} // Output: "/path/to/file.txt"

func (*FunctionHandler) PathDir

func (fh *FunctionHandler) PathDir(str string) string

PathDir returns all but the last element of the path, effectively the path's directory.

Parameters:

str string - the path string.

Returns:

string - the directory part of the path.

Example:

{{ "/path/to/file.txt" | pathDir }} // Output: "/path/to"

func (*FunctionHandler) PathExt

func (fh *FunctionHandler) PathExt(str string) string

PathExt returns the file extension of the path.

Parameters:

str string - the path string.

Returns:

string - the extension of the file in the path.

Example:

{{ "/path/to/file.txt" | pathExt }} // Output: ".txt"

func (*FunctionHandler) PathIsAbs

func (fh *FunctionHandler) PathIsAbs(str string) bool

PathIsAbs checks if the path is absolute.

Parameters:

str string - the path string.

Returns:

bool - true if the path is absolute, otherwise false.

Example:

{{ "/path/to/file.txt" | pathIsAbs }} // Output: true

func (*FunctionHandler) PemBlockForKey

func (fh *FunctionHandler) PemBlockForKey(priv interface{}) *pem.Block

func (*FunctionHandler) Pick

func (fh *FunctionHandler) Pick(dict map[string]any, keys ...string) map[string]any

Pick creates a new dictionary containing only the specified keys from the original dictionary.

Parameters:

dict map[string]any - the source dictionary.
keys ...string - the keys to include in the new dictionary.

Returns:

map[string]any - a dictionary containing only the picked keys and their values.

Example:

{{ pick {"key1": "value1", "key2": "value2", "key3": "value3"}, "key1", "key3" }} // Output: {"key1": "value1", "key3": "value3"}

func (*FunctionHandler) Pluck

func (fh *FunctionHandler) Pluck(key string, dicts ...map[string]any) []any

Pluck extracts values associated with a specified key from a list of dictionaries.

Parameters:

key string - the key to pluck values for.
dicts ...map[string]any - one or more dictionaries.

Returns:

[]any - a list of values associated with the key from each dictionary.

Example:

{{ [{"key": "value1"}, {"key": "value2"}] | pluck "key" }} // Output: ["value1", "value2"]

func (*FunctionHandler) Plural

func (fh *FunctionHandler) Plural(one, many string, count int) string

Plural returns 'one' if 'count' is 1, otherwise it returns 'many'.

Parameters:

one string - the string to return if 'count' is 1.
many string - the string to return if 'count' is not 1.
count int - the number used to determine which string to return.

Returns:

string - either 'one' or 'many' based on 'count'.

Example:

{{ 1 | plural "apple" "apples" }} // Output: "apple"
{{ 2 | plural "apple" "apples" }} // Output: "apples"

func (*FunctionHandler) Prepend

func (fh *FunctionHandler) Prepend(list any, v any) []any

Prepend adds an element to the beginning of the list.

Parameters:

list any - the original list to prepend to.
v any - the element to prepend.

Returns:

[]any - the new list with the element prepended.

Example:

{{ prepend  ["b", "c"], "a" }} // Output: ["a", "b", "c"]

func (*FunctionHandler) Quote

func (fh *FunctionHandler) Quote(elements ...any) string

Quote wraps each element in 'elements' with double quotes and separates them with spaces.

Parameters:

elements ...any - the elements to be quoted.

Returns:

string - a single string with each element double quoted.

Example:

 {{ $list := slice "hello" "world" 123 }}
	{{ $list | quote }}
	Output: "hello" "world" "123"

func (*FunctionHandler) RandAlpha

func (fh *FunctionHandler) RandAlpha(count int) string

RandAlpha generates a random alphabetic string of specified length.

Parameters:

count int - the length of the string to generate.

Returns:

string - the randomly generated alphabetic string.

Example:

{{ 10 | randAlpha }} // Output: "abcdefghij" (output will vary)

func (*FunctionHandler) RandAlphaNumeric

func (fh *FunctionHandler) RandAlphaNumeric(count int) string

RandAlphaNumeric generates a random alphanumeric string of specified length.

Parameters:

count int - the length of the string to generate.

Returns:

string - the randomly generated alphanumeric string.

Example:

{{ 10 | randAlphaNumeric }} // Output: "a1b2c3d4e5" (output will vary)

func (*FunctionHandler) RandAscii

func (fh *FunctionHandler) RandAscii(count int) string

RandAscii generates a random ASCII string (character codes 32 to 126) of specified length.

Parameters:

count int - the length of the string to generate.

Returns:

string - the randomly generated ASCII string.

Example:

{{ 10 | randAscii }} // Output: "}]~>_<:^%" (output will vary)

func (*FunctionHandler) RandBytes

func (fh *FunctionHandler) RandBytes(count int) (string, error)

RandBytes generates a random byte array of specified length and returns it as a base64 encoded string.

Parameters:

count int - the number of bytes to generate.

Returns:

string - the base64 encoded string of the randomly generated bytes.
error - error if the random byte generation fails.

Example:

{{ 16 | randBytes }} // Output: "c3RhY2thYnVzZSByb2NrcyE=" (output will vary)

func (*FunctionHandler) RandInt

func (fh *FunctionHandler) RandInt(min, max int) int

func (*FunctionHandler) RandNumeric

func (fh *FunctionHandler) RandNumeric(count int) string

RandNumeric generates a random numeric string of specified length.

Parameters:

count int - the length of the string to generate.

Returns:

string - the randomly generated numeric string.

Example:

{{ 10 | randNumeric }} // Output: "0123456789" (output will vary)

func (*FunctionHandler) RegexFind

func (fh *FunctionHandler) RegexFind(regex string, s string) string

RegexFind returns the first match of the regex pattern in the string.

Parameters:

regex string - the regular expression pattern to search for.
s string - the string to search.

Returns:

string - the first matching string.

Example:

{{ regexFind "a(b+)" "aaabbb" }} // Output: "abbb"

func (*FunctionHandler) RegexFindAll

func (fh *FunctionHandler) RegexFindAll(regex string, s string, n int) []string

RegexFindAll returns all matches of the regex pattern in the string up to n matches.

Parameters:

regex string - the regular expression pattern to search for.
s string - the string to search.
n int - the maximum number of matches to return.

Returns:

[]string - a slice of all matches.

Example:

{{ regexFindAll "a(b+)" "aaabbb" 2 }} // Output: ["abbb"]

func (*FunctionHandler) RegexMatch

func (fh *FunctionHandler) RegexMatch(regex string, s string) bool

RegexMatch checks if the string matches the regex pattern.

Parameters:

regex string - the regular expression pattern to match against.
s string - the string to check.

Returns:

bool - true if the string matches the regex pattern, otherwise false.

Example:

{{ regexMatch "^[a-zA-Z]+$" "Hello" }} // Output: true

func (*FunctionHandler) RegexQuoteMeta

func (fh *FunctionHandler) RegexQuoteMeta(s string) string

RegexQuoteMeta returns a literal pattern string for the provided string.

Parameters:

s string - the string to be escaped.

Returns:

string - the escaped regex pattern.

Example:

{{ regexQuoteMeta ".+*?^$()[]{}|" }} // Output: "\.\+\*\?\^\$\(\)\[\]\{\}\|"

func (*FunctionHandler) RegexReplaceAll

func (fh *FunctionHandler) RegexReplaceAll(regex string, s string, repl string) string

RegexReplaceAll replaces all occurrences of the regex pattern in the string with the replacement string.

Parameters:

regex string - the regular expression pattern to replace.
s string - the string to perform replacements on.
repl string - the replacement string.

Returns:

string - the string with all replacements made.

Example:

{{ regexReplaceAll "[aeiou]" "hello" "i" }} // Output: "hillo"

func (*FunctionHandler) RegexReplaceAllLiteral

func (fh *FunctionHandler) RegexReplaceAllLiteral(regex string, s string, repl string) string

RegexReplaceAllLiteral replaces all occurrences of the regex pattern in the string with the literal replacement string.

Parameters:

regex string - the regular expression pattern to replace.
s string - the string to perform replacements on.
repl string - the replacement string, inserted literally.

Returns:

string - the string with all replacements made, without treating the replacement string as a regex replacement pattern.

Example:

{{ regexReplaceAllLiteral "[aeiou]" "hello" "$&" }} // Output: "h$&ll$&"

func (*FunctionHandler) RegexSplit

func (fh *FunctionHandler) RegexSplit(regex string, s string, n int) []string

RegexSplit splits the string by the regex pattern up to n times.

Parameters:

regex string - the regular expression pattern to split by.
s string - the string to split.
n int - the number of times to split.

Returns:

[]string - a slice of the substrings split by the regex.

Example:

{{regexSplit "\\s+" "hello world" -1 }} // Output: ["hello", "world"]

func (*FunctionHandler) Repeat

func (fh *FunctionHandler) Repeat(count int, str string) string

Repeat repeats the string 'str' for 'count' times.

Parameters:

count int - the number of times to repeat.
str string - the string to repeat.

Returns:

string - the repeated string.

Example:

{{ "ha" | repeat 3 }} // Output: "hahaha"

func (*FunctionHandler) Replace

func (fh *FunctionHandler) Replace(old, new, src string) string

Replace replaces all occurrences of 'old' in 'src' with 'new'.

Parameters:

old string - the substring to be replaced.
new string - the substring to replace with.
src string - the source string where replacements take place.

Returns:

string - the modified string after all replacements.

Example:

{{ "banana" | replace "a", "o" }} // Output: "bonono"

func (*FunctionHandler) Rest

func (fh *FunctionHandler) Rest(list any) []any

Rest returns all elements of a list except the first.

Parameters:

list any - the list to process.

Returns:

[]any - the list without the first element.

Example:

{{ [1, 2, 3, 4] | rest }} // Output: [2, 3, 4]

func (*FunctionHandler) Reverse

func (fh *FunctionHandler) Reverse(list any) []any

Reverse returns a new list with the elements in reverse order.

Parameters:

list any - the list to reverse.

Returns:

[]any - the list in reverse order.

Example:

{{ [1, 2, 3, 4] | reverse }} // Output: [4, 3, 2, 1]

func (*FunctionHandler) Round

func (fh *FunctionHandler) Round(num any, poww int, roundOpts ...float64) float64

Round rounds a number to a specified precision and rounding threshold.

Parameters:

num any - the number to round.
poww int - the power of ten to which to round.
roundOpts ...float64 - optional threshold for rounding up (default is 0.5).

Returns:

float64 - the rounded number.

Example:

{{ 3.746, 2, 0.5 | round }} // Output: 3.75

func (*FunctionHandler) Semver

func (fh *FunctionHandler) Semver(version string) (*sv2.Version, error)

func (*FunctionHandler) SemverCompare

func (fh *FunctionHandler) SemverCompare(constraint, version string) (bool, error)

func (*FunctionHandler) Seq

func (fh *FunctionHandler) Seq(params ...int) string

Seq generates a sequence of numbers as a string. It can take 0, 1, 2, or 3 integers as parameters defining the start, end, and step of the sequence. NOTE: This function works similarly to the seq command in Unix systems.

Parameters:

params ...int - sequence parameters (start, step, end).

Returns:

string - a space-separated string of numbers in the sequence.

Example:

{{ seq 1, 2, 10 }} // Output: "1 3 5 7 9"

func (*FunctionHandler) Set

func (fh *FunctionHandler) Set(dict map[string]any, key string, value any) map[string]any

Set adds or updates a key with a specified value in the dictionary.

Parameters:

dict map[string]any - the dictionary.
key string - the key to set.
value any - the value to associate with the key.

Returns:

map[string]any - the updated dictionary.

Example:

{{ set {"key": "oldValue"}, "key", "newValue" }} // Output: {"key": "newValue"}

func (*FunctionHandler) Sha1sum

func (fh *FunctionHandler) Sha1sum(input string) string

func (*FunctionHandler) Sha256sum

func (fh *FunctionHandler) Sha256sum(input string) string

////////// CRYPTO // //////////

func (*FunctionHandler) Shuffle

func (fh *FunctionHandler) Shuffle(str string) string

Shuffle randomly rearranges the characters in 'str'.

Parameters:

str string - the string to shuffle.

Returns:

string - the shuffled string.

Example:

{{ "hello" | shuffle }} // Output: "loleh" (output may vary due to randomness)

func (*FunctionHandler) Slice

func (fh *FunctionHandler) Slice(list any, indices ...any) any

Slice extracts a slice from a list between two indices.

Parameters:

list any - the list to slice.
indices ...any - the start and optional end indices; if end is omitted,

slices to the end.

Returns:

any - the sliced part of the list.

Example:

{{ slice [1, 2, 3, 4, 5], 1, 3 }} // Output: [2, 3]

func (*FunctionHandler) SortAlpha

func (fh *FunctionHandler) SortAlpha(list any) []string

SortAlpha sorts a list of strings in alphabetical order.

Parameters:

list any - the list of strings to sort.

Returns:

[]string - the sorted list.

Example:

{{ ["d", "b", "a", "c"] | sortAlpha }} // Output: ["a", "b", "c", "d"]

func (*FunctionHandler) Split

func (fh *FunctionHandler) Split(sep, orig string) map[string]string

Split divides 'orig' into a map of string parts using 'sep' as the separator.

Parameters:

sep string - the separator string.
orig string - the original string to split.

Returns:

map[string]string - a map of the split parts.

Example:

{{ "apple,banana,cherry" | split "," }} // Output: { "_0":"apple", "_1":"banana", "_2":"cherry" }

func (*FunctionHandler) SplitList

func (fh *FunctionHandler) SplitList(sep string, str string) []string

SplitList divides a string into a slice of substrings separated by the specified separator.

! FUTURE: Rename this function to be more explicit

Parameters:

sep string - the delimiter used to split the string.
str string - the string to split.

Returns:

[]string - a slice containing the substrings obtained from splitting the input string.

Example:

{{ ", ", "one, two, three" | splitList }} // Output: ["one", "two", "three"]

func (*FunctionHandler) Splitn

func (fh *FunctionHandler) Splitn(sep string, n int, orig string) map[string]string

Splitn divides 'orig' into a map of string parts using 'sep' as the separator up to 'n' parts.

Parameters:

sep string - the separator string.
n int - the maximum number of substrings to return.
orig string - the original string to split.

Returns:

map[string]string - a map of the split parts.

Example:

{{ "apple,banana,cherry" | split "," 2 }} // Output: { "_0":"apple", "_1":"banana,cherry" }

func (*FunctionHandler) Squote

func (fh *FunctionHandler) Squote(elements ...any) string

Squote wraps each element in 'elements' with single quotes and separates them with spaces.

Parameters:

elements ...any - the elements to be single quoted.

Returns:

string - a single string with each element single quoted.

Example:

 {{ $list := slice "hello" "world" 123 }}
	{{ $list | squote }}
Output: 'hello' 'world' '123'

func (*FunctionHandler) StrSlice

func (fh *FunctionHandler) StrSlice(value any) []string

func (*FunctionHandler) Sub

func (fh *FunctionHandler) Sub(values ...any) any

Sub performs subtraction on a slice of values, starting with the first value.

Parameters:

values ...any - numbers to subtract from the first number.

Returns:

any - the result of the subtraction, converted to the type of the first value.

Example:

{{ 10, 3, 2 | sub }} // Output: 5

func (*FunctionHandler) Substring

func (fh *FunctionHandler) Substring(start, end int, str string) string

Substring extracts a substring from 's' starting at 'start' and ending at 'end'. Negative values for 'start' or 'end' are interpreted as positions from the end of the string.

Parameters:

start int - the starting index.
end int - the ending index, exclusive.
str string - the source string.

Returns:

string - the extracted substring.

Example:

{{ "Hello World" | substring 0 5 }} // Output: "Hello"

func (*FunctionHandler) SwapCase

func (fh *FunctionHandler) SwapCase(str string) string

SwapCase switches the case of each letter in 'str'. Lowercase letters become uppercase and vice versa.

Parameters:

str string - the string to convert.

Returns:

string - the string with each character's case switched.

Example:

{{ "Hello World" | swapCase }} // Output: "hELLO wORLD"

func (*FunctionHandler) Ternary

func (fh *FunctionHandler) Ternary(trueValue any, falseValue any, condition bool) any

Ternary mimics the ternary conditional operator found in many programming languages. It returns 'trueValue' if 'condition' is true, otherwise 'falseValue'.

Parameters:

trueValue any - the value to return if 'condition' is true.
falseValue any - the value to return if 'condition' is false.
condition bool - the condition to evaluate.

Returns:

any - the result based on the evaluated condition.

Example:

{{ "yes", "no", true | ternary }} // Output: "yes"
{{ "yes", "no", false | ternary }} // Output: "no"

func (*FunctionHandler) ToBool added in v0.4.0

func (fh *FunctionHandler) ToBool(v any) bool

ToBool converts a value to a boolean.

Parameters:

v any - the value to convert to a boolean. This can be any types reasonably be converted to true or false.

Returns:

bool - the boolean representation of the value.

Example:

{{ "true" | toBool }} // Output: true

func (*FunctionHandler) ToCamelCase

func (fh *FunctionHandler) ToCamelCase(str string) string

ToCamelCase converts a string to camelCase.

Parameters:

str string - the string to convert.

Returns:

string - the string converted to camelCase.

Example:

{{ "hello world" | toCamelCase }} // Output: "helloWorld"

func (*FunctionHandler) ToConstantCase

func (fh *FunctionHandler) ToConstantCase(str string) string

ToConstantCase converts a string to CONSTANT_CASE.

Parameters:

str string - the string to convert.

Returns:

string - the string converted to CONSTANT_CASE.

Example:

{{ "hello world" | toConstantCase }} // Output: "HELLO_WORLD"

func (*FunctionHandler) ToDate

func (fh *FunctionHandler) ToDate(fmt, str string) time.Time

ToDate converts a string to a time.Time object based on a format specification.

Parameters:

fmt string - the date format string.
str string - the date string to parse.

Returns:

time.Time - the parsed date.

Example:

{{ "2006-01-02", "2023-05-04" | toDate }} // Output: 2023-05-04 00:00:00 +0000 UTC

func (*FunctionHandler) ToDotCase

func (fh *FunctionHandler) ToDotCase(str string) string

ToDotCase converts a string to dot.case.

Parameters:

str string - the string to convert.

Returns:

string - the string converted to dot.case.

Example:

{{ "hello world" | toDotCase }} // Output: "hello.world"

func (*FunctionHandler) ToDuration

func (fh *FunctionHandler) ToDuration(v any) time.Duration

ToDuration converts a value to a time.Duration.

Parameters:

v any - the value to convert to time.Duration. This value can be a string, int, or another compatible type.

Returns:

time.Duration - the duration representation of the value.

Example:

{{ (toDuration "1h30m").Seconds }} // Output: 5400

func (*FunctionHandler) ToFloat64

func (fh *FunctionHandler) ToFloat64(v any) float64

ToFloat64 converts a value to a float64.

Parameters:

v any - the value to convert to a float64.

Returns:

float64 - the float64 representation of the value.

Example:

{{ "123.456" | toFloat64 }} // Output: 123.456

func (*FunctionHandler) ToInt

func (fh *FunctionHandler) ToInt(v any) int

ToInt converts a value to an int using robust type casting.

Parameters:

v any - the value to convert to an int.

Returns:

int - the integer representation of the value.

Example:

{{ "123" | toInt }} // Output: 123

func (*FunctionHandler) ToInt64

func (fh *FunctionHandler) ToInt64(v any) int64

ToInt64 converts a value to an int64, accommodating larger integer values.

Parameters:

v any - the value to convert to an int64.

Returns:

int64 - the int64 representation of the value.

Example:

{{ "123456789012" | toInt64 }} // Output: 123456789012

func (*FunctionHandler) ToJson

func (fh *FunctionHandler) ToJson(v any) string

ToJson converts a Go data structure into a JSON string.

Parameters:

v any - the Go data structure to encode.

Returns:

string - the encoded JSON string.

Example:

jsonStr := fh.ToJson(map[string]any{"name": "John", "age": 30})
fmt.Println(jsonStr) // Output: {"age":30,"name":"John"}

func (*FunctionHandler) ToKebabCase

func (fh *FunctionHandler) ToKebabCase(str string) string

ToKebabCase converts a string to kebab-case.

Parameters:

str string - the string to convert.

Returns:

string - the string converted to kebab-case.

Example:

{{ "hello world" | toKebabCase }} // Output: "hello-world"

func (*FunctionHandler) ToLower

func (fh *FunctionHandler) ToLower(str string) string

ToLower converts all characters in the provided string to lowercase.

Parameters:

str string - the string to convert.

Returns:

string - the lowercase version of the input string.

Example:

{{ "HELLO WORLD" | toLower }} // Output: "hello world"

func (*FunctionHandler) ToOctal

func (fh *FunctionHandler) ToOctal(v any) int64

ToOctal parses a string value as an octal (base 8) integer.

Parameters:

v any - the string representing an octal number.

Returns:

int64 - the decimal (base 10) representation of the octal value.
If parsing fails, returns 0.

Example:

{{ "123" | toOctal }} // Output: 83 (since "123" in octal is 83 in decimal)

func (*FunctionHandler) ToPascalCase

func (fh *FunctionHandler) ToPascalCase(str string) string

ToPascalCase converts a string to PascalCase.

Parameters:

str string - the string to convert.

Returns:

string - the string converted to PascalCase.

Example:

{{ "hello world" | toPascalCase }} // Output: "HelloWorld"

func (*FunctionHandler) ToPathCase

func (fh *FunctionHandler) ToPathCase(str string) string

ToPathCase converts a string to path/case.

Parameters:

str string - the string to convert.

Returns:

string - the string converted to path/case.

Example:

{{ "hello world" | toPathCase }} // Output: "hello/world"

func (*FunctionHandler) ToPrettyJson

func (fh *FunctionHandler) ToPrettyJson(v any) string

ToPrettyJson converts a Go data structure into a pretty-printed JSON string.

Parameters:

v any - the Go data structure to encode.

Returns:

string - the pretty-printed JSON string.

Example:

prettyJson := fh.ToPrettyJson(map[string]any{"name": "John", "age": 30})
fmt.Println(prettyJson) // Output: {
                        //   "age": 30,
                        //   "name": "John"
                        // }

func (*FunctionHandler) ToRawJson

func (fh *FunctionHandler) ToRawJson(v any) string

ToRawJson converts a Go data structure into a JSON string without escaping HTML.

Parameters:

v any - the Go data structure to encode.

Returns:

string - the raw JSON string.

Example:

rawJson := fh.ToRawJson(map[string]any{"content": "<div>Hello World!</div>"})
fmt.Println(rawJson) // Output: {"content":"<div>Hello World!</div>"}

func (*FunctionHandler) ToSnakeCase

func (fh *FunctionHandler) ToSnakeCase(str string) string

ToSnakeCase converts a string to snake_case.

Parameters:

str string - the string to convert.

Returns:

string - the string converted to snake_case.

Example:

{{ "hello world" | toSnakeCase }} // Output: "hello_world"

func (*FunctionHandler) ToString

func (fh *FunctionHandler) ToString(v any) string

ToString converts a value to a string, handling various types effectively.

Parameters:

v any - the value to convert to a string.

Returns:

string - the string representation of the value.

Example:

{{ 123 | toString }} // Output: "123"

func (*FunctionHandler) ToTitleCase

func (fh *FunctionHandler) ToTitleCase(str string) string

ToTitleCase converts a string to Title Case.

Parameters:

str string - the string to convert.

Returns:

string - the string converted to Title Case.

Example:

{{ "hello world" | toTitleCase }} // Output: "Hello World"

func (*FunctionHandler) ToUint added in v0.4.0

func (fh *FunctionHandler) ToUint(v any) uint

ToUint converts a value to a uint.

Parameters:

v any - the value to convert to uint. This value can be of any type that is numerically convertible.

Returns:

uint - the uint representation of the value.

Example:

{{ "123" | toUint }} // Output: 123

func (*FunctionHandler) ToUint64 added in v0.4.0

func (fh *FunctionHandler) ToUint64(v any) uint64

ToUint64 converts a value to a uint64.

Parameters:

v any - the value to convert to uint64. This value can be of any type that is numerically convertible.

Returns:

uint64 - the uint64 representation of the value.

Example:

{{ "123456789012345" | toUint64 }} // Output: 123456789012345

func (*FunctionHandler) ToUpper

func (fh *FunctionHandler) ToUpper(str string) string

ToUpper converts all characters in the provided string to uppercase.

Parameters:

str string - the string to convert.

Returns:

string - the uppercase version of the input string.

Example:

{{ "hello world" | toUpper }} // Output: "HELLO WORLD"

func (*FunctionHandler) ToYAML added in v0.4.0

func (fh *FunctionHandler) ToYAML(v any) string

ToYAML serializes a Go data structure to a YAML string.

Parameters:

v any - the data structure to serialize.

Returns:

string - the YAML string representation of the data structure.

Example:

{{ {"name": "John Doe", "age": 30} | toYAML }} // Output: "name: John Doe\nage: 30\n"

func (*FunctionHandler) Trim

func (fh *FunctionHandler) Trim(str string) string

Trim removes leading and trailing whitespace from the string.

Parameters:

str string - the string to trim.

Returns:

string - the trimmed string.

Example:

{{ " Hello World " | trim }} // Output: "Hello World"

func (*FunctionHandler) TrimAll

func (fh *FunctionHandler) TrimAll(cutset string, str string) string

TrimAll removes all occurrences of any characters in 'cutset' from both the beginning and the end of 'str'.

Parameters:

cutset string - a string of characters to remove from the string.
str string - the string to trim.

Returns:

string - the string with specified characters removed.

Example:

{{ "xyzHelloxyz" | trimAll "xyz" }} // Output: "Hello"

func (*FunctionHandler) TrimPrefix

func (fh *FunctionHandler) TrimPrefix(prefix string, str string) string

TrimPrefix removes the 'prefix' from the start of 'str' if present.

Parameters:

prefix string - the prefix to remove.
str string - the string to trim.

Returns:

string - the string with the prefix removed if it was present.

Example:

{{ "HelloWorld" | trimPrefix "Hello" }} // Output: "World"

func (*FunctionHandler) TrimSuffix

func (fh *FunctionHandler) TrimSuffix(suffix string, str string) string

TrimSuffix removes the 'suffix' from the end of 'str' if present.

Parameters:

suffix string - the suffix to remove.
str string - the string to trim.

Returns:

string - the string with the suffix removed if it was present.

Example:

{{ "HelloWorld" | trimSuffix "World" }} // Output: "Hello"

func (*FunctionHandler) Trunc

func (fh *FunctionHandler) Trunc(count int, str string) string

Trunc truncates 's' to a maximum length 'count'. If 'count' is negative, it removes '-count' characters from the beginning of the string.

Parameters:

count int - the number of characters to keep. Negative values indicate truncation
            from the beginning.
str string - the string to truncate.

Returns:

string - the truncated string.

Example:

{{ "Hello World" | trunc 5 }} // Output: "Hello"
{{ "Hello World" | trunc -1 }} // Output: "World"

func (*FunctionHandler) TypeIs

func (fh *FunctionHandler) TypeIs(target string, src any) bool

TypeIs compares the type of 'src' to a target type string 'target'. It returns true if the type of 'src' matches the 'target'.

Parameters:

target string - the string representation of the type to check against.
src any - the variable whose type is being checked.

Returns:

bool - true if 'src' is of type 'target', false otherwise.

Example:

{{ "int", 42 | typeIs }} // Output: true

func (*FunctionHandler) TypeIsLike

func (fh *FunctionHandler) TypeIsLike(target string, src any) bool

TypeIsLike compares the type of 'src' to a target type string 'target', including a wildcard '*' prefix option. It returns true if 'src' matches 'target' or '*target'. Useful for checking if a variable is of a specific type or a pointer to that type.

Parameters:

target string - the string representation of the type or its wildcard version.
src any - the variable whose type is being checked.

Returns:

bool - true if the type of 'src' matches 'target' or '*'+target, false otherwise.

Example:

{{ "*int", 42 | typeIsLike }} // Output: true

func (*FunctionHandler) TypeOf

func (fh *FunctionHandler) TypeOf(src any) string

TypeOf returns the type of 'src' as a string.

Parameters:

src any - the variable whose type is being determined.

Returns:

string - the string representation of 'src's type.

Example:

{{ 42 | typeOf }} // Output: "int"

func (*FunctionHandler) Uniq

func (fh *FunctionHandler) Uniq(list any) []any

Uniq removes duplicate elements from a list.

Parameters:

list any - the list from which to remove duplicates.

Returns:

[]any - a list containing only unique elements.

Example:

{{ ["a", "b", "a", "c"] | uniq }} // Output: ["a", "b", "c"]

func (*FunctionHandler) UnixEpoch

func (fh *FunctionHandler) UnixEpoch(date time.Time) string

UnixEpoch returns the Unix epoch timestamp of a given date.

Parameters:

date time.Time - the date to convert to a Unix timestamp.

Returns:

string - the Unix timestamp as a string.

Example:

{{ now | unixEpoch }} // Output: "1683306245"

func (*FunctionHandler) Unset

func (fh *FunctionHandler) Unset(dict map[string]any, key string) map[string]any

Unset removes a key from the dictionary.

Parameters:

dict map[string]any - the dictionary.
key string - the key to remove.

Returns:

map[string]any - the dictionary after removing the key.

Example:

{{ {"key": "value"}, "key" | unset }} // Output: {}

func (*FunctionHandler) Until

func (fh *FunctionHandler) Until(count int) []int

func (*FunctionHandler) UntilStep

func (fh *FunctionHandler) UntilStep(start, stop, step int) []int

UntilStep generates a slice of integers from 'start' to 'stop' (exclusive), incrementing by 'step'. If 'step' is positive, the sequence increases; if negative, it decreases. The function returns an empty slice if the sequence does not make logical sense (e.g., positive step when start is greater than stop or vice versa).

Parameters:

start int - the starting point of the sequence.
stop int - the endpoint (exclusive) of the sequence.
step int - the increment between elements in the sequence.

Returns:

[]int - a dynamically generated slice of integers based on the input
        parameters, or an empty slice if the parameters are inconsistent
        with the desired range and step.

Example:

{{ 0, 10, 2 | untilStep }} // Output: [0 2 4 6 8]
{{ 10, 0, -2 | untilStep }} // Output: [10 8 6 4 2]

func (*FunctionHandler) Untitle

func (fh *FunctionHandler) Untitle(str string) string

Untitle converts the first letter of each word in 'str' to lowercase.

Parameters:

str string - the string to be converted.

Returns:

string - the converted string with each word starting in lowercase.

Example:

{{ "Hello World" | untitle }} // Output: "hello world"

func (*FunctionHandler) UrlJoin

func (fh *FunctionHandler) UrlJoin(d map[string]any) string

func (*FunctionHandler) UrlParse

func (fh *FunctionHandler) UrlParse(v string) map[string]any

func (*FunctionHandler) Uuidv4

func (fh *FunctionHandler) Uuidv4() string

Uuidv4 generates a new random UUID (Universally Unique Identifier) version 4. This function does not take parameters and returns a string representation of a UUID.

Returns:

string - a new UUID string.

Example:

{{ uuidv4 }} // Output: "3f0c463e-53f5-4f05-a2ec-3c083aa8f937"

func (*FunctionHandler) Values

func (fh *FunctionHandler) Values(dict map[string]any) []any

Values retrieves all values from a dictionary.

Parameters:

dict map[string]any - the dictionary.

Returns:

[]any - a list of all values from the dictionary.

Example:

{{ values {"key1": "value1", "key2": "value2"} }} // Output: ["value1", "value2"]

func (*FunctionHandler) Without

func (fh *FunctionHandler) Without(list any, omit ...any) []any

Without returns a new list excluding specified elements.

Parameters:

list any - the original list.
omit ...any - elements to exclude from the new list.

Returns:

[]any - the list excluding the specified elements.

Example:

{{ without [1, 2, 3, 4], 2, 4 }} // Output: [1, 3]

func (*FunctionHandler) WordWrap

func (fh *FunctionHandler) WordWrap(wrapLength int, newLineCharacter string, wrapLongWords bool, str string) string

WordWrap formats 'str' into lines of maximum 'wrapLength', optionally wrapping long words and using 'newLineCharacter' for line breaks.

Parameters:

str string - the string to wrap.
wrapLength int - the maximum length of each line.
newLineCharacter string - the string used to denote new lines.
wrapLongWords bool - true to wrap long words that exceed the line length.

Returns:

string - the wrapped string.

Example:

{{ "A very longwordindeed that cannot fit on one line." | wordWrap 10 "\n" true }}
Output: "A very\nlongwordin\ndeed that\ncannot fit\non one\nline."

func (*FunctionHandler) Wrap

func (fh *FunctionHandler) Wrap(length int, str string) string

Wrap breaks 'str' into lines with a maximum length of 'length'. It ensures that words are not split across lines unless necessary.

Parameters:

length int - the maximum length of each line.
str string - the string to be wrapped.

Returns:

string - the wrapped string using newline characters to separate lines.

Example:

{{ "This is a long string that needs to be wrapped." | wrap 10 }}
Output: "This is a\nlong\nstring\nthat needs\nto be\nwrapped."

func (*FunctionHandler) WrapWith

func (fh *FunctionHandler) WrapWith(length int, newLineCharacter string, str string) string

WrapWith breaks 'str' into lines of maximum 'length', using 'newLineCharacter' to separate lines. It wraps words only when they exceed the line length.

Parameters:

length int - the maximum line length.
newLineCharacter string - the character(s) used to denote new lines.
str string - the string to wrap.

Returns:

string - the wrapped string.

Example:

{{ "This is a long string that needs to be wrapped." | wrapWith 10 "<br>" }}
Output: "This is a<br>long<br>string<br>that needs<br>to be<br>wrapped."

type FunctionHandlerOption

type FunctionHandlerOption func(*FunctionHandler)

FunctionHandlerOption defines a type for functional options that configure FunctionHandler.

func WithAlias

func WithAlias(originalFunction string, aliases ...string) FunctionHandlerOption

WithAlias returns a FunctionHandlerOption that associates one or more alias names with an original function name. This allows the function to be called by any of its aliases.

originalFunction specifies the original function name to which aliases will be added. aliases is a variadic parameter that takes one or more strings as aliases for the original function.

The function does nothing if no aliases are provided. If the original function name does not already have associated aliases in the FunctionHandler, a new slice of strings is created to hold its aliases. Each provided alias is then appended to this slice.

This option must be applied to a FunctionHandler using the FunctionHandler's options mechanism for the aliases to take effect.

Example:

handler := NewFunctionHandler(WithAlias("originalFunc", "alias1", "alias2"))

func WithAliases

func WithAliases(aliases FunctionAliasMap) FunctionHandlerOption

WithAliases returns a FunctionHandlerOption that configures multiple aliases for function names in a single call. It allows a batch of functions to be associated with their respective aliases, facilitating the creation of aliases for multiple functions at once.

This option must be applied to a FunctionHandler using the FunctionHandler's options mechanism for the aliases to take effect. It complements the WithAlias function by providing a means to configure multiple aliases in one operation, rather than one at a time.

Example:

handler := NewFunctionHandler(WithAliases(sprout.FunctionAliasMap{
    "originalFunc1": {"alias1_1", "alias1_2"},
    "originalFunc2": {"alias2_1", "alias2_2"},
}))

func WithErrHandling

func WithErrHandling(eh ErrHandling) FunctionHandlerOption

WithErrHandling sets the error handling strategy for a FunctionHandler.

func WithErrorChannel

func WithErrorChannel(ec chan error) FunctionHandlerOption

WithErrorChannel sets the error channel for a FunctionHandler.

func WithFunctionHandler

func WithFunctionHandler(new *FunctionHandler) FunctionHandlerOption

WithFunctionHandler updates a FunctionHandler with settings from another FunctionHandler. This is useful for copying configurations between handlers.

func WithLogger

func WithLogger(l *slog.Logger) FunctionHandlerOption

WithLogger sets the logger used by a FunctionHandler.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL