### Install Sprout Package Source: https://github.com/go-sprout/sprout/blob/main/docs/introduction/getting-started.md Install the Sprout package using the get command. ```bash get -u github.com/go-sprout/sprout ``` -------------------------------- ### Install Sprout Go Package Source: https://context7.com/go-sprout/sprout/llms.txt Use 'go get' to install or update the Sprout library. ```bash go get -u github.com/go-sprout/sprout ``` -------------------------------- ### Quick Sprout Example with text/template Source: https://github.com/go-sprout/sprout/blob/main/README.md A minimal example demonstrating how to use Sprout with the text/template package. It initializes a handler, adds a standard registry, builds the function map, and executes a simple template. ```go package main import ( os "text/template" "github.com/go-sprout/sprout" "github.com/go-sprout/sprout/registry/std" ) func main() { handler := sprout.New() handler.AddRegistry(std.NewRegistry()) tpl := template.Must( template.New("example").Funcs(handler.Build()).Parse(`{{ hello }}`), ) tpl.Execute(os.Stdout, nil) } ``` -------------------------------- ### Complete Go Sprout Application Example Source: https://context7.com/go-sprout/sprout/llms.txt This example demonstrates setting up a Go Sprout handler with multiple registries, defining a complex template string, and rendering it with provided data. It showcases common template functions for reporting and data manipulation. ```go package main import ( "bytes" "fmt" "text/template" "github.com/go-sprout/sprout" "github.com/go-sprout/sprout/group/all" ) func main() { // Create handler with all registries handler := sprout.New( sprout.WithAlias("toUpper", "upper"), sprout.WithSafeFuncs(true), ) handler.AddGroup(all.RegistryGroup()) // Build function map funcs := handler.Build() // Define template tmplStr := ` Configuration Report ===================== Generated: {{ now | date "2006-01-02 15:04:05" }} Report ID: {{ uuidv4 }} User Information: Name: {{ .User.Name | toTitleCase }} Email: {{ .User.Email | toLower }} ID Hash: {{ .User.Email | sha256Sum | trunc 8 }} Settings: {{- range $key, $value := .Settings }} - {{ $key }}: {{ $value }} {{- end }} Features Enabled: {{ .Features | join ", " }} Feature Count: {{ .Features | len }} Environment: Debug: {{ .Debug | ternary "Enabled" "Disabled" }} Version: {{ .Version | default "1.0.0" }} ` // Parse template tmpl := template.Must( template.New("report").Funcs(funcs).Parse(tmplStr), ) // Data data := map[string]any{ "User": map[string]string{ "Name": "john doe", "Email": "John.Doe@Example.COM", }, "Settings": map[string]any{ "theme": "dark", "language": "en", "timezone": "UTC", }, "Features": []string{"auth", "logging", "caching"}, "Debug": true, "Version": "", } // Execute template var buf bytes.Buffer if err := tmpl.Execute(&buf, data); err != nil { panic(err) } fmt.Println(buf.String()) } ``` -------------------------------- ### Template Example for Deep Copy Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/reflect.md Demonstrates using the deepCopy function within a template. The first example shows a successful deep copy of a map, while the second illustrates how a nil input results in an error. ```go {{ dict "name" "John" | deepCopy }} // Output: map[name:John] {{ nil | deepCopy }} // Error ``` -------------------------------- ### Call FUNCTION_NAME Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/registryname.md Example of calling FUNCTION_NAME with its implementation. Ensure the registry is imported. ```go {{ FUNCTION_IMPLEM }} // Output: FUNCTION_OUTPUT ``` -------------------------------- ### Hello Function Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/std.md Use the `hello` function to get a simple greeting string. It's useful for verifying system functionality. ```go {{ hello }} ``` -------------------------------- ### Go Function Registration Examples Source: https://github.com/go-sprout/sprout/blob/main/docs/introduction/templating-conventions.md Illustrates naming conventions for function registration and their corresponding Go function signatures, including transformation, boolean, and error-returning functions. ```go "toCamelCase" -> toCamelCase(str string) string ``` ```go "toUpperCase" -> toUpperCase(str string) string ``` ```go "toInt" -> toInt(str string) (int, error) ``` ```go "isValid" -> isValid() bool ``` ```go "isEmpty" -> isEmpty(str string) bool ``` ```go "hasKey" -> hasKey() bool ``` ```go "hasItems" -> hasItems() bool ``` -------------------------------- ### Example of mergeOverwrite in Go Template Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/maps.md This example demonstrates merging two dictionaries in a Go template using mergeOverwrite. The output shows the combined map with values from the second dictionary overwriting common keys. ```go {{- $d1 := dict "a" 1 "b" 2 -}} {{- $d2 := dict "b" 3 "c" 4 -}} {{ mergeOverwrite $d1 $d2 }} // Output: map[a:1 b:3 c:4] ``` -------------------------------- ### Go Template Unescape Examples Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/strings.md Demonstrates the usage of the unescape function within Go templates. It shows how to unescape characters like '.' and ':' from strings. ```go {{ unescape "." "example\\.com" }} // Output: example.com ``` ```go {{ unescape ".:" "a\\.b\\:c" }} // Output: a.b:c ``` ```go {{ "example.com" | escape "." | unescape "." }} // Output: example.com ``` -------------------------------- ### Go Sprout String Functions: Substring and Indentation Source: https://context7.com/go-sprout/sprout/llms.txt Illustrates extracting substrings using start and end indices, and indenting multi-line strings. ```go // Substring and indentation {{ "Hello World" | substr 0 5 }} // Output: Hello {{ "Hello\nWorld" | indent 4 }} ``` -------------------------------- ### Add Function Example Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/numeric.md Sums all elements in a slice of values. Returns 0 for an empty slice and handles various numeric types. ```go {{ add }} // Output: 0 {{ add 1 }} // Output: 1 {{ add 1 2 3 4 5 6 7 8 9 10 }} // Output: 55 {{ add 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.1 }} // Output: 59.6 ``` -------------------------------- ### Get Path Extension Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/filesystem.md Use `pathExt` to retrieve the file extension from a given path string. ```go {{ "/" | pathExt }} // Output: "" {{ "/path/to/file.txt" | pathExt }} // Output: ".txt" ``` -------------------------------- ### Use Custom Handler with Templates in Go Source: https://github.com/go-sprout/sprout/blob/main/docs/advanced/how-to-create-a-handler.md Instantiate your custom handler, add a registry, build the function map, parse a template, and execute it. This example assumes 'myFunc' is registered. ```go handler := NewMyCustomHandler() handler.AddRegistry(std.NewRegistry()) tpl, err := template.New("example").Funcs(handler.Build()).Parse(`{{ myFunc }}`) if err != nil { log.Fatal(err) } tpl.Execute(os.Stdout, nil) ``` -------------------------------- ### Convert to Unsigned Int64 - Template Example Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/conversion.md Use `toUint64` to convert values to a 64-bit unsigned integer. This function handles string, float, and boolean inputs. Errors are returned for invalid conversions. ```go {{ "1" | toUint64 }} // Output: 1 {{ 1.1 | toUint64 }} // Output: 1 {{ true | toUint64 }} // Output: 1 {{ "invalid" | toUint64 }} // Error ``` -------------------------------- ### Add1 Function Example Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/numeric.md Performs unary addition, incrementing the provided value by one. Handles numeric types. ```go {{ add1 -1 }} // Output: 0 {{ add1 1 }} // Output: 2 {{ add1 1.1 }} // Output: 2.1 ``` -------------------------------- ### Check for Prefix with hasPrefix Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/strings.md Use `hasPrefix` to determine if a string begins with a specific prefix. This is useful for conditional logic based on the start of a string. ```go {{ "HelloWorld" | hasPrefix "Hello" }} // Output: true ``` -------------------------------- ### Get Initial Part of List in Go Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/slices.md Returns all elements of a list except the last one. Input must be a list. ```go {{ list 1 2 3 4 | initial }} // Output: [1 2 3] ``` ```go {{ initial 1 }} // Error ``` -------------------------------- ### Convert String to Path Case Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/strings.md Use `toPathCase` to convert a string to path/case format. Example: "hello world" becomes "hello/world". ```go {{ "hello world" | toPathCase }} // Output: hello/world ``` -------------------------------- ### Go Sprout String Functions: String Manipulation Source: https://context7.com/go-sprout/sprout/llms.txt Provides examples of common string manipulation tasks such as replacing characters, repeating strings, truncating, and adding ellipses. ```go // String manipulation {{ "banana" | replace "a" "o" }} // Output: bonono {{ "ha" | repeat 3 }} // Output: hahaha {{ "Hello World" | trunc 5 }} // Output: Hello {{ "Hello World" | ellipsis 8 }} ``` -------------------------------- ### Convert String to Kebab Case Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/strings.md Use `toKebabCase` to convert a string to kebab-case format. Example: "hello world" becomes "hello-world". ```go {{ "hello world" | toKebabCase }} // Output: hello-world ``` -------------------------------- ### Sub Function Example Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/numeric.md Performs subtraction on a slice of values, starting with the first and subtracting subsequent values. Handles numeric types. ```go {{ sub 10 3 2 }} // Output: 5 ``` -------------------------------- ### Convert String to Pascal Case Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/strings.md Use `toPascalCase` to convert a string to PascalCase format. Example: "hello world" becomes "HelloWorld". ```go {{ "hello world" | toPascalCase }} // Output: HelloWorld ``` -------------------------------- ### Get Path Directory Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/filesystem.md Use `pathDir` to get all but the last element of a path, effectively extracting the directory portion. ```go {{ "/" | pathDir }} // Output: "/" {{ "/path/to/file.txt" | pathDir }} // Output: "/path/to" ``` -------------------------------- ### Convert to Float64 - Template Example Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/conversion.md The `toFloat64` function converts values to a 64-bit floating-point number. It supports string, float, and boolean inputs. Errors occur for invalid conversions. ```go {{ "1" | toFloat64 }} // Output: 1 {{ 1.42 | toFloat64 }} // Output: 1.42 {{ true | toFloat64 }} // Output: 1 {{ "invalid" | toFloat64 }} // Error ``` -------------------------------- ### Map Functions: get, set, unset, hasKey, pick, omit Source: https://github.com/go-sprout/sprout/blob/main/docs/migration-from-sprig.md Illustrates the Sprout signature for map manipulation functions, which uses the pipe operator for chaining. ```go {{ get $dict "key" }} ``` ```go {{ $dict | get "key" }} ``` ```go {{ set $dict "key" "value" }} ``` ```go {{ $dict | set "key" "value" }} ``` ```go {{ unset $dict "key" }} ``` ```go {{ $dict | unset "key" }} ``` ```go {{ hasKey $dict "key" }} ``` ```go {{ $dict | hasKey "key" }} ``` ```go {{ pick $dict "k1" "k2" }} ``` ```go {{ $dict | pick "k1" "k2" }} ``` ```go {{ omit $dict "k1" "k2" }} ``` ```go {{ $dict | omit "k1" "k2" }} ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/go-sprout/sprout/blob/main/docs/introduction/templating-conventions.md Examples of Git commit messages following the Conventional Commits specification for clear and structured commit history. ```git fix: resolve issue with time registry ``` ```git feat: add toSpace functions in galaxy registry ``` ```git docs: update README with installation instructions ``` -------------------------------- ### Retrieve Value from Dictionary with Get Function Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/maps.md Use the `get` function to retrieve a value by its key from a map. It returns the value and an error if the key is not found. ```go {{ dict "key" "value" | get "key" }} // Output: "value" {{ dict "key" "value" | get "invalid" }} // Output: "" ``` -------------------------------- ### Get OS-Specific Path Directory Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/filesystem.md Use `osDir` to get all but the last element of a path, using the operating system's specific path separator. ```go {{ "C:\\path\\to\\file.txt" | osDir }} // Output(will be different): "C:\\path\\to" ``` -------------------------------- ### Standard Utility Functions in Go Templates Source: https://context7.com/go-sprout/sprout/llms.txt Use these functions for conditional logic, value handling, and basic string operations within Go templates. They require no special setup beyond including the standard registry. ```go // Template examples for standard functions: // Hello function (test) {{ hello }} // Output: Hello! ``` ```go // Default values {{ "" | default "fallback" }} // Output: fallback {{ "value" | default "fallback" }} // Output: value {{ .MissingKey | default "none" }} // Output: none ``` ```go // Empty check {{ "" | empty }} // Output: true {{ 0 | empty }} // Output: true {{ false | empty }} // Output: true {{ "hello" | empty }} // Output: false ``` ```go // All values non-empty {{ all 1 "hello" true }} // Output: true {{ all 1 "" true }} // Output: false ``` ```go // Any value non-empty {{ any "" 0 false }} // Output: false {{ any "" 0 "text" }} // Output: true ``` ```go // First non-empty value {{ coalesce nil "" "first" "second" }} // Output: first ``` ```go // Ternary conditional {{ true | ternary "yes" "no" }} // Output: yes {{ false | ternary "yes" "no" }} // Output: no ``` ```go // Concatenate values {{ cat "Hello" 123 true }} // Output: Hello 123 true ``` -------------------------------- ### get - Retrieve Value from Dictionary Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/maps.md The `get` function retrieves the value associated with a specified key from a dictionary (map). If the key is found, the corresponding value is returned. ```APIDOC ## get ### Description Retrieves the value associated with a specified key from a dictionary (map). ### Signature `Get(key string, dict map[string]any) (any, error)` ### Template Example ```go {{ dict "key" "value" | get "key" }} // Output: "value" {{ dict "key" "value" | get "invalid" }} // Output: "" ``` ``` -------------------------------- ### Get OS-Specific Path Base Name Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/filesystem.md Use `osBase` to get the last element of a path, respecting the operating system's specific path separator. ```go {{ "C:\\path\\to\\file.txt" | osBase }} // Output(will be different): "file.txt" ``` -------------------------------- ### Go Sprout String Functions: Splitting and Joining Source: https://context7.com/go-sprout/sprout/llms.txt Demonstrates how to split strings into slices based on a delimiter and join slices into strings with a specified separator. ```go // Splitting and joining {{ "a,b,c" | split "," }} // Output: map[_0:a _1:b _2:c] {{- $list := list "a" "b" "c" -}} {{ $list | join ", " }} ``` -------------------------------- ### Create and Manipulate Dictionaries in Go Templates Source: https://context7.com/go-sprout/sprout/llms.txt Use `dict` to create maps. `get`, `set`, and `unset` modify existing maps. `hasKey` checks for key existence. `keys` and `values` extract map elements. `pick` and `omit` filter maps. `dig` accesses nested values. `merge` and `mergeOverwrite` combine maps. `pluck` extracts values from multiple maps. ```go // Creating dictionaries {{ dict "name" "John" "age" 30 }} // Output: map[age:30 name:John] ``` ```go // Getting and setting values {{- $d := dict "name" "John" -}} {{ $d | get "name" }} // Output: John {{ $d | set "age" 30 }} // Output: map[age:30 name:John] {{ $d | unset "name" }} // Output: map[] ``` ```go // Checking keys {{- $d := dict "name" "John" -}} {{ $d | hasKey "name" }} // Output: true {{ $d | hasKey "age" }} // Output: false ``` ```go // Keys and values {{- $d := dict "a" 1 "b" 2 -}} {{ keys $d | sortAlpha }} // Output: [a b] {{ values $d }} // Output: [1 2] ``` ```go // Filtering dictionaries {{- $d := dict "a" 1 "b" 2 "c" 3 -}} {{ $d | pick "a" "c" }} // Output: map[a:1 c:3] {{ $d | omit "b" }} // Output: map[a:1 c:3] ``` ```go // Accessing nested values with dig {{- $d := dict "user" (dict "name" "John" "address" (dict "city" "NYC")) -}} {{ $d | dig "user" "name" }} // Output: John {{ $d | dig "user.address.city" }} // Output: NYC ``` ```go // Merging dictionaries {{- $d1 := dict "a" 1 "b" 2 -}} {{- $d2 := dict "b" 3 "c" 4 -}} {{ merge $d1 $d2 }} // Output: map[a:1 b:2 c:4] {{ mergeOverwrite $d1 $d2 }} // Output: map[a:1 b:3 c:4] ``` ```go // Extracting values from multiple dicts {{- $d1 := dict "id" 1 -}} {{- $d2 := dict "id" 2 -}} {{ pluck "id" $d1 $d2 }} // Output: [1 2] ``` -------------------------------- ### Convert String to Title Case Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/strings.md Use `toTitleCase` to convert a string to Title Case format. Example: "hello world" becomes "Hello World". ```go {{ "hello world" | toTitleCase }} // Output: Hello World ``` -------------------------------- ### Untitle String Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/strings.md Use `untitle` to convert the first letter of each word in a string to lowercase. Example: "Hello World" becomes "hello world". ```go {{ "Hello World" | untitle }} // Output: hello world ``` -------------------------------- ### Build Custom Certificate Source: https://github.com/go-sprout/sprout/blob/main/sprigin/compatibility/README.md Builds a custom certificate. ```go buildCustomCert ``` -------------------------------- ### Create Handler and Build Function Map Source: https://context7.com/go-sprout/sprout/llms.txt Demonstrates creating a Sprout handler, adding individual registries (standard, strings, conversion), building a function map, and using it with Go's text/template. ```go package main import ( "os" "text/template" "github.com/go-sprout/sprout" "github.com/go-sprout/sprout/registry/std" "github.com/go-sprout/sprout/registry/strings" "github.com/go-sprout/sprout/registry/conversion" ) func main() { // Create a new handler handler := sprout.New() // Add individual registries handler.AddRegistries( std.NewRegistry(), strings.NewRegistry(), conversion.NewRegistry(), ) // Build the function map funcs := handler.Build() // Use with templates tmpl := template.Must( template.New("example").Funcs(funcs).Parse(` Hello from Sprout! Name: {{ .Name | toUpper }} Greeting: {{ hello }} `)) tmpl.Execute(os.Stdout, map[string]string{"Name": "world"}) // Output: // Hello from Sprout! // Name: WORLD // Greeting: Hello! } ``` -------------------------------- ### Generate Number Sequence (Go) Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/strings.md The `seq` function generates a string of numbers based on start, step, and end parameters, mimicking the Unix `seq` command. It handles various parameter combinations, including empty calls. ```go {{ seq 1 2 10 }} // Output: 1 3 5 7 9 {{ seq 3 -3 2 }} // Output: 3 {{ seq }} // Output: "" {{ seq 0 4 }} // Output: 0 1 2 3 4 {{ seq -5 }} // Output: 1 0 -1 -2 -3 -4 -5 {{ seq 0 -4 }} // Output: 0 -1 -2 -3 -4 ``` -------------------------------- ### Go Sprout Slice Functions: Creating Lists Source: https://context7.com/go-sprout/sprout/llms.txt Demonstrates the basic creation of lists (slices) with integer and string elements. ```go // Creating lists {{ list 1 2 3 }} {{ list "a" "b" "c" }} ``` -------------------------------- ### Create an Info Notice Source: https://github.com/go-sprout/sprout/blob/main/docs/features/function-notices.md Use `NewInfoNotice` to create a purely informational notice. This notice is linked to `slog.InfoLevel` and is useful for general messages. ```go sprout.NewInfoNotice("toLower", "This is an informative notice") ``` -------------------------------- ### Get Value Type as String Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/reflect.md Returns the data type of a value as a string. ```go {{ 42 | typeOf }} // Output: "int" ``` -------------------------------- ### Run Benchmarks (Sprig v3.2.3 vs Sprout v0.5) Source: https://github.com/go-sprout/sprout/blob/main/benchmarks/README.md Command to execute benchmarks and capture detailed performance metrics. Results indicate Sprout v0.5 is 45.3% faster and uses 16.5% less memory. ```bash go test -count=1 -bench ^Benchmark -benchmem -cpuprofile cpu.out -memprofile mem.out goos: linux goarch: amd64 pkg: sprout_benchmarks cpu: Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz BenchmarkSprig-16 1 2991811373 ns/op 50522680 B/op 32649 allocs/op BenchmarkSprout-16 1 1638797544 ns/op 42171152 B/op 18061 allocs/op PASS ok sprout_benchmarks 4.921s ``` -------------------------------- ### Create a List Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/slices.md Use the `list` function to create an array-like structure from provided elements. ```go {{ list 1 2 3 }} // Output: [1 2 3] ``` -------------------------------- ### Get First Element of List Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/slices.md The `First` function returns the first element of a list. ```APIDOC ## Get First Element of List ### Description Returns the first element of a list. ### Signature `First(list any) (any, error)` ### Parameters #### Query Parameters - **list** (any) - Required - The list from which to get the first element. ### Request Example ```go {{ list 1 2 3 4 | first }} ``` ### Response Example ```go 1 ``` ### Error Handling - Returns an error if the input `list` is nil or empty. ``` -------------------------------- ### Initialize Sprout Handler for New Projects Source: https://github.com/go-sprout/sprout/blob/main/docs/migration-from-sprig.md Use this for new projects or when breaking changes are acceptable. It provides all Sprout improvements without compatibility overhead. ```go import "github.com/go-sprout/sprout" handler := sprout.New() funcs := handler.Build() ``` -------------------------------- ### Use Registry Groups for Comprehensive Functionality Source: https://context7.com/go-sprout/sprout/llms.txt Shows how to add all standard registries at once using a registry group and then use various functions like toUpper, join, date, and randAlphaNum within a template. ```go package main import ( "os" "text/template" "github.com/go-sprout/sprout" "github.com/go-sprout/sprout/group/all" ) func main() { // Create handler with all registries at once handler := sprout.New() handler.AddGroup(all.RegistryGroup()) funcs := handler.Build() tmpl := template.Must( template.New("demo").Funcs(funcs).Parse(` {{ "hello world" | toUpper }} {{ list 1 2 3 | join ", " }} {{ now | date "2006-01-02" }} {{ randAlphaNum 8 }} `)) tmpl.Execute(os.Stdout, nil) // Output (dates/random will vary): // HELLO WORLD // 1, 2, 3 // 2025-01-15 // aB3xK9mZ } ``` -------------------------------- ### Get Rest of List Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/slices.md The `Rest` function returns all elements of a list except for the first one. ```APIDOC ## Get Rest of List ### Description Returns all elements of a list except for the first one, effectively giving you the "rest" of the list. ### Signature `Rest(list any) ([]any, error)` ### Parameters #### Query Parameters - **list** (any) - Required - The list from which to get the rest of the elements. ### Request Example ```go {{ list 1 2 3 4 | rest }} ``` ### Response Example ```go [2 3 4] ``` ### Error Handling - Returns an error if the input `list` is nil or not a list. ``` -------------------------------- ### Run Benchmarks (Sprig v3.2.3 vs Sprout v0.3) Source: https://github.com/go-sprout/sprout/blob/main/benchmarks/README.md Command to execute benchmarks and capture detailed performance metrics. Results indicate Sprout v0.3 is 52.6% faster and uses 15.1% less memory. ```bash go test -count=1 -bench ^Benchmark -benchmem -cpuprofile cpu.out -memprofile mem.out 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 ``` -------------------------------- ### Slice List Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/slices.md The `Slice` function extracts a portion of a list based on start and end indices. ```APIDOC ## Slice List ### Description Extracts a portion of a list, creating a new slice based on the specified start and end indices. ### Signature `Slice(indices ...any, list any) (any, error)` ### Parameters #### Query Parameters - **indices** (any) - Required - The start and end indices for the slice. - **list** (any) - Required - The list to slice. ### Request Example ```go {{ list 1 2 3 4 5 | slice 1 3 }} ``` ### Response Example ```go [2 3] ``` ``` -------------------------------- ### Import Network Registry Functions Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/network.md Include this import statement to use all functions from the network registry. ```go import "github.com/go-sprout/sprout/registry/network" ``` -------------------------------- ### Run Benchmarks (Sprig v3.2.3 vs Sprout v0.2) Source: https://github.com/go-sprout/sprout/blob/main/benchmarks/README.md Command to execute benchmarks and capture detailed performance metrics. Results indicate Sprout v0.2 is 53.1% faster and uses 15.7% less memory. ```bash go test -count=1 -bench ^Benchmark -benchmem -cpuprofile cpu.out -memprofile mem.out goos: linux goarch: amd64 pkg: sprout_benchmarks cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz BenchmarkSprig-12 1 3869134593 ns/op 45438616 B/op 24098 allocs/op BenchmarkSprout-12 1 1814126036 ns/op 38284040 B/op 11627 allocs/op PASS ok sprout_benchmarks 5.910s ``` -------------------------------- ### Get Initial Part of List Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/slices.md The `Initial` function returns all elements of a list except for the last one. ```APIDOC ## Get Initial Part of List ### Description Returns all elements of a list except the last one, effectively providing the "initial" portion of the list. ### Signature `Initial(list any) ([]any, error)` ### Parameters #### Query Parameters - **list** (any) - Required - The list from which to get the initial elements. ### Request Example ```go {{ list 1 2 3 4 | initial }} ``` ### Response Example ```go [1 2 3] ``` ### Error Handling - Returns an error if the input `list` is nil or not a list. ``` -------------------------------- ### Initialize Handler with Notices Source: https://github.com/go-sprout/sprout/blob/main/docs/features/function-notices.md When creating a new handler, use `sprout.WithNotices` to pass in defined notices. The handler will automatically assign these notices to the appropriate functions during the `Build()` process. ```go handler := sprout.New(sprout.WithNotices(notice)) ``` -------------------------------- ### Get First Element of List in Go Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/slices.md Returns the first element of a list. Input must be a list. ```go {{ list 1 2 3 4 | first }} // Output: 1 ``` ```go {{ first nil }} // Error ``` -------------------------------- ### Divf - Float Division Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/numeric.md Divides a sequence of values, starting with the first value, and returns the result as a float64. ```APIDOC ## Divf ### Description Divides a sequence of values, starting with the first value, and returns the result as a `float64`. ### Signature `Divf(values ...any) (any, error)` ### Example ```go {{ divf 30.0 3.0 2.0 }} {{ 2 | divf 5 4 }} ``` ### Output `5` `0.625` ``` -------------------------------- ### Import Random Registry Functions Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/random.md Include this import statement to use all functions from the random registry. ```go import "github.com/go-sprout/sprout/registry/random" ``` -------------------------------- ### Go Sprout Slice Functions: Generating Sequences Source: https://context7.com/go-sprout/sprout/llms.txt Shows how to generate sequences of numbers up to a limit using `until` and sequences with a specific step using `untilStep`. ```go // Generating sequences {{ until 5 }} {{ untilStep 0 10 2 }} ``` -------------------------------- ### Get Last Element of a List Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/slices.md Returns the last element of a list. Handles nil input by returning an error. ```go Last(list any) (any, error) ``` ```go {{ list 1 2 3 4 | last }} // Output: 4 {{ last nil }} // Error ``` -------------------------------- ### Get Rest of List in Go Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/slices.md Returns all elements of a list except the first one. Input must be a list. ```go {{ list 1 2 3 4 | rest }} // Output: [2 3 4] ``` ```go {{ rest 1 }} // Error ``` -------------------------------- ### Import Regexp Registry Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/regexp.md Include this import statement to use all functions from the regexp registry. ```go import "github.com/go-sprout/sprout/registry/regexp" ``` -------------------------------- ### Slice a List in Go Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/slices.md Extracts a portion of a list based on start and end indices. The end index is exclusive. ```go {{ list 1 2 3 4 5 | slice 1 3 }} // Output: [2 3] ``` -------------------------------- ### Import Semver Registry Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/semver.md Include this import statement to use all functions from the semver registry. ```go import "github.com/go-sprout/sprout/registry/semver" ``` -------------------------------- ### Go Sprout Slice Functions: Slicing Source: https://context7.com/go-sprout/sprout/llms.txt Shows how to extract a sub-slice from a list using start and end indices. ```go // Slicing {{ list 1 2 3 4 5 | slice 1 3 }} ``` -------------------------------- ### Configure Sprout Handler Options Source: https://context7.com/go-sprout/sprout/llms.txt Illustrates configuring a Sprout handler with custom logger, function aliases, deprecation notices, safe functions mode, and loading registries during initialization. ```go package main import ( "log/slog" "os" "github.com/go-sprout/sprout" "github.com/go-sprout/sprout/registry/std" "github.com/go-sprout/sprout/registry/strings" ) func main() { logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) handler := sprout.New( // Custom logger for debugging sprout.WithLogger(logger), // Function aliases for backward compatibility sprout.WithAlias("toUpper", "upper", "uppercase"), sprout.WithAlias("toLower", "lower", "lowercase"), // Add deprecation notices sprout.WithNotices( sprout.NewDeprecatedNotice("oldFunc", "Use newFunc instead"), sprout.NewInfoNotice("debug", "Debug function called"), ), // Enable safe functions (continue on error, log instead of fail) sprout.WithSafeFuncs(true), // Load registries during initialization sprout.WithRegistries( std.NewRegistry(), strings.NewRegistry(), ), ) funcs := handler.Build() // funcs now contains all configured functions with aliases } ``` -------------------------------- ### Go Sprout Slice Functions: Adding Elements Source: https://context7.com/go-sprout/sprout/llms.txt Shows how to add elements to the end of a list using append and to the beginning using prepend. ```go // Adding elements {{ list "a" "b" | append "c" }} {{ list "b" "c" | prepend "a" }} ``` -------------------------------- ### Get Current Time Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/time.md Returns the current time as a time.Time object. The output format will vary based on the current time. ```go {{ now }} // Output(will be different): "2023-05-07T15:04:05Z" ``` -------------------------------- ### Import Backward Registry Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/backward.md Include this import statement to use all functions from the backward registry. ```go import "github.com/go-sprout/sprout/registry/backward" ``` -------------------------------- ### Compare Semver Versions Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/semver.md Check if a version string satisfies a semantic version constraint according to Semantic Versioning rules. ```go {{ semverCompare ">=1.0.0" "1.0.0" }} // Output: true {{ semverCompare "1.0.0" "1.0.0" }} // Output: true {{ semverCompare "1.0.0" "1.0.1" }} // Output: false {{ semverCompare "~1.0.0" "1.0.0" }} // Output: true {{ semverCompare ">1.0.0-alpha" "1.0.0-alpha.1" }} // Output: true {{ semverCompare "1.0.0-alpha.1" "1.0.0-alpha" }} // Output: false {{ semverCompare "1.0.0-alpha.1" "1.0.0-alpha.1" }} // Output: true ``` -------------------------------- ### Get Environment Variable Value Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/env.md Retrieves the value of a specified environment variable. Returns an empty string if the variable is not set. ```go {{ env "INVALID" }} // Output: "" ``` ```go {{ "PATH" | env }} // Output(will be different): "/usr/bin:/bin:/usr/sbin:/sbin" ``` -------------------------------- ### Std Registry Functions Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/std.md This section details the functions available within the Std registry, including their signatures and usage examples. ```APIDOC ## Std Registry Functions The Std registry provides a set of standard functions for common tasks, included by default, making it easy to perform basic operations without additional setup. You can import all functions from the `std` registry using: `import "github.com/go-sprout/sprout/registry/std"` ### hello **Description**: Returns a simple greeting string, "Hello!". Useful for verifying system functionality. **Signature**: `Hello() string` **Template Example**: ```go {{ hello }} ``` ### default **Description**: Returns the first non-empty value from a list of arguments. If the list is empty or the first value is empty, it returns a specified default value. For finding the first non-empty value from multiple options, use `Coalesce`. **Signature**: `Default(defaultValue any, given ...any) any` **Template Example**: ```go {{ .Nil | default "default" }} {{ "" | default "default" }} {{ "first" | default "default" }} {{ "first" | default "default" "second" }} ``` ### empty **Description**: Checks if the provided value is empty based on its type. Returns `true` if the value is considered empty. **Signature**: `Empty(given any) bool` **Template Example**: ```go {{ .Nil | empty }} {{ "" | empty }} {{ 0 | empty }} {{ false | empty }} {{ .Struct | empty }} ``` ### all **Description**: Checks if all values in a variadic slice are non-empty. Returns `true` only if every value is considered non-empty. **Signature**: `All(values ...any) bool` **Template Example**: ```go {{ all 1 "hello" true }} {{ all 1 "" true }} ``` ### any **Description**: Checks if any of the provided values are non-empty. Returns `true` if at least one value is considered non-empty. **Signature**: `Any(values ...any) bool` **Template Example**: ```go {{ any "" 0 false }} {{ any "" 0 "text" }} ``` ### coalesce **Description**: Returns the first non-empty value from the provided list. If all values are empty, it returns `nil`. **Signature**: `Coalesce(values ...any) any` **Template Example**: ```go {{ coalesce nil "" "first" "second" }} ``` ``` -------------------------------- ### Get Value Kind as String Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/reflect.md Returns the kind (category) of a value as a string, such as 'int', 'struct', or 'slice'. May return an error. ```go {{ 42 | kindOf }} // Output: "int" {{ nil | kindOf }} // Error ``` -------------------------------- ### Import Numeric Registry Functions Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/numeric.md Import all functions from the numeric registry to use them in your code. ```go import "github.com/go-sprout/sprout/registry/numeric" ``` -------------------------------- ### Get Path Base Name Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/filesystem.md Use `pathBase` to extract the last element (file or directory name) from a given path string. ```go {{ "/path/to/file.txt" | pathBase }} // Output: "file.txt" ``` -------------------------------- ### Import Env Registry Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/env.md Include this import statement to use functions from the env registry. ```go import "github.com/go-sprout/sprout/registry/env" ``` -------------------------------- ### Initialize Custom Handler in Go Source: https://github.com/go-sprout/sprout/blob/main/docs/advanced/how-to-create-a-handler.md Create a constructor function to initialize your custom handler with a logger and empty maps/slices. It sets up the logger to write to standard output. ```go func NewMyCustomHandler() *MyCustomHandler { return &MyCustomHandler{ logger: slog.New(slog.NewTextHandler(os.Stdout)), registries: make([]sprout.Registry, 0), funcsMap: make(sprout.FunctionMap), funcsAlias: make(sprout.FunctionAliasMap), } } ``` -------------------------------- ### Import Filesystem Registry Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/filesystem.md Include this import statement to use functions from the filesystem registry in your Go code. ```go import "github.com/go-sprout/sprout/registry/filesystem" ``` -------------------------------- ### Import Reflect Registry Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/reflect.md Import all functions from the reflect registry to use them in your Go code. ```go import "github.com/go-sprout/sprout/registry/reflect" ``` -------------------------------- ### Divide Sequence of Values (float64) Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/numeric.md Divides a sequence of values, starting with the first, and returns the result as a float64. Use this for precise floating-point division. ```go {{ divf 30.0 3.0 2.0 }} // Output: 5 ``` ```go {{ 2 | divf 5 4 }} // Output: 0.625 ``` -------------------------------- ### Add Registries to Sprout Handler Source: https://github.com/go-sprout/sprout/blob/main/docs/features/loader-system-registry.md Initialize a Sprout handler and add one or more registries. This setup is necessary before building the FunctionMap for template processing. ```go handler := sprout.New() // Add one registry handler.AddRegistry(ownregistry.NewRegistry()) // Add more than one at the same time handler.AddRegistries( ownregistry.NewRegistry(), // ... ) // Build your FunctionMap based on your handler tpl := template.Must( template.New("base").Funcs(handler.Build()).ParseGlob("*.tmpl"), ) ``` -------------------------------- ### Import Std Registry Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/std.md Import all functions from the `std` registry by including this statement in your Go code. ```go import "github.com/go-sprout/sprout/registry/std" ``` -------------------------------- ### Transition from Sprig to Sprout Source: https://github.com/go-sprout/sprout/blob/main/README.md Replace the Sprig import with sprigin for backward compatibility. For new projects, use the Sprout package directly. ```diff import ( - "github.com/Masterminds/sprig/v3" + "github.com/go-sprout/sprout/sprigin" ) tpl := template.Must( template.New("base"). - Funcs(sprig.FuncMap()). + Funcs(sprigin.FuncMap()). ParseGlob("*.tmpl") ) ``` -------------------------------- ### Format Current Time in Go Templates Source: https://context7.com/go-sprout/sprout/llms.txt Use the `now` function to get the current timestamp. Format it using various predefined layouts or custom formats. ```go // Current time {{ now }} // Output: 2024-05-10 15:04:05 +0000 UTC ``` ```go // Date formatting {{ now | date "2006-01-02" }} // Output: 2024-05-10 {{ now | date "Jan 2, 2006" }} // Output: May 10, 2024 {{ now | date "15:04:05" }} // Output: 15:04:05 ``` ```go // Date with timezone {{- $d := now -}} {{ dateInZone "2006-01-02 15:04" $d "America/New_York" }} // Output: 2024-05-10 11:04 ``` ```go // HTML date format {{ now | htmlDate }} // Output: 2024-05-10 ``` ```go // Unix timestamp {{ now | unixEpoch }} // Output: 1715353445 ``` -------------------------------- ### Configure Sprout Handler with Registry Groups Source: https://github.com/go-sprout/sprout/blob/main/docs/introduction/getting-started.md Initialize a Sprout handler and load a group of registries using the WithGroups option. ```go import "github.com/go-sprout/sprout" handler := sprout.New(sprout.WithGroups(ownregistrygroup.RegistryGroup())) ``` -------------------------------- ### Get Unix Epoch Timestamp Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/time.md Returns the Unix epoch timestamp as a string for a given date.Time object. The output will differ based on the current time. ```go {{ now | unixEpoch }} // Output(will be different): 1683306245 ``` -------------------------------- ### Get Last IP Address from CIDR Block Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/network.md CIDRLast returns the last IP address within a specified IPv4 or IPv6 CIDR block. ```go {{ cidrLast "10.42.0.0/24" }} // Output: 10.42.0.255 ``` ```go {{ cidrLast "2001:db8::/32" }} // Output: 2001:db8:ffff:ffff:ffff:ffff:ffff:ffff ``` -------------------------------- ### Go Project Directory Structure Source: https://github.com/go-sprout/sprout/blob/main/docs/introduction/templating-conventions.md Standard directory layout for the go-sprout/sprout project, outlining the purpose of each top-level directory. ```bash ├── benchmarks/ # benchmarks used to ensure performance and backward ├── docs/ # documentation of the project hosted on sprout.atom.codes ├── internal/helpers/ # private cross registry library code ├── pesticide/ # package to help you to test your functions on a template engine ├── registry/ # contains all officials registry of sprout └── sprigin/ # TEMPORARY backward compatibility package with sprig ``` -------------------------------- ### Get First IP Address from CIDR Block Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/network.md CIDRFirst returns the first IP address within a specified IPv4 or IPv6 CIDR block. ```go {{ cidrFirst "10.42.0.0/24" }} // Output: 10.42.0.0 ``` ```go {{ cidrFirst "2001:db8::/32" }} // Output: 2001:db8:: ``` -------------------------------- ### Create a Debug Notice with Output Placeholder Source: https://github.com/go-sprout/sprout/blob/main/docs/features/function-notices.md Use `NewDebugNotice` for debugging purposes. The message can include the `$out` placeholder, which will be replaced with the actual output of the function. This notice is linked to `slog.DebugLevel`. ```go sprout.NewDebugNotice("toLower", "toLower result are $out") ``` -------------------------------- ### Go Code Formatting Command Source: https://github.com/go-sprout/sprout/blob/main/docs/introduction/templating-conventions.md Run this command to format your Go code according to standard conventions before committing. ```bash go fmt ./... ``` -------------------------------- ### Get All Values from Dictionaries with Values Function Source: https://github.com/go-sprout/sprout/blob/main/docs/registries/maps.md Use the `values` function to retrieve all values from one or more maps as a slice. The values can be sorted for consistent output. ```go {{- $d := dict "key1" "value1" "key2" "value2" -}} {{ values $d | sortAlpha }} // Output: [value1 value2] ```