Documentation
¶
Overview ¶
Package filter provides template filter functions for transforming data in template rendering pipelines. It supports:
- String manipulation: case conversion, truncation, slugification
- Array operations: unique, sort, shuffle, aggregation
- Date formatting: date parsing, component extraction, relative time
- Number formatting: numeric formatting, byte humanization
- Math operations: arithmetic, rounding, clamping
All functions accept interface{} inputs for maximum flexibility in dynamic template contexts.
Index ¶
- Variables
- func Abs(input any) (float64, error)
- func Append(input, toAppend string) string
- func AtLeast(input, minimum any) (float64, error)
- func AtMost(input, maximum any) (float64, error)
- func Average(input any) (float64, error)
- func Base64Decode(input string) (string, error)
- func Base64Encode(input string) string
- func Bytes(input any) (string, error)
- func Camelize(input string) string
- func Capitalize(input string) string
- func Ceil(input any) (float64, error)
- func Compact(input any, key ...string) ([]any, error)
- func Concat(input, other any) ([]any, error)
- func Dasherize(input string) string
- func Date(input any, format string) (string, error)
- func Day(input any) (int, error)
- func Default(input, defaultValue any) any
- func Divide(input, divisor any) (float64, error)
- func Escape(input string) string
- func EscapeOnce(input string) string
- func Extract(input any, key string) (any, error)
- func Find(input any, key string, value any) (any, error)
- func FindIndex(input any, key string, value any) (int, error)
- func First(input any) (any, error)
- func Floor(input any) (float64, error)
- func Has(input any, key string, value ...any) (bool, error)
- func Index(input any, index int) (any, error)
- func Join(input any, separator string) (string, error)
- func Last(input any) (any, error)
- func Length(input string) int
- func Lower(input string) string
- func Map(input any, key string) ([]any, error)
- func Max(input any) (float64, error)
- func Min(input any) (float64, error)
- func Minus(input, subtrahend any) (float64, error)
- func Modulo(input, modulus any) (float64, error)
- func Month(input any) (int, error)
- func MonthFull(input any) (string, error)
- func Number(input any, format string) (string, error)
- func Ordinalize(number int) string
- func Pascalize(input string) string
- func Pluralize(count int, singular, plural string) string
- func Plus(input, addend any) (float64, error)
- func Prepend(input, toPrepend string) string
- func Random(input any) (any, error)
- func Reject(input any, key string, value ...any) ([]any, error)
- func Remove(input, toRemove string) string
- func RemoveFirst(input, toRemove string) string
- func RemoveLast(input, toRemove string) string
- func Replace(input, old, replacement string) string
- func ReplaceFirst(input, old, replacement string) string
- func ReplaceLast(input, old, replacement string) string
- func Reverse(input any) ([]any, error)
- func Round(input, precision any) (float64, error)
- func Shuffle(input any) ([]any, error)
- func Size(input any) (int, error)
- func Slice(input any, offset int, length ...int) (any, error)
- func Slugify(input string) string
- func Sort(input any, key ...string) ([]any, error)
- func SortNatural(input any, key ...string) ([]any, error)
- func Split(input, delimiter string) []string
- func StripHTML(input string) string
- func StripNewlines(input string) string
- func Sum(input any) (float64, error)
- func TimeAgo(input any) (string, error)
- func Times(input, multiplier any) (float64, error)
- func Titleize(input string) string
- func Trim(input string) string
- func TrimLeft(input string) string
- func TrimRight(input string) string
- func Truncate(input string, maxLength int, ellipsis ...string) string
- func TruncateWords(input string, maxWords int, ellipsis ...string) string
- func URLDecode(input string) (string, error)
- func URLEncode(input string) string
- func Unique(input any) ([]any, error)
- func Upper(input string) string
- func Week(input any) (int, error)
- func Weekday(input any) (string, error)
- func Where(input any, key string, value ...any) ([]any, error)
- func Year(input any) (int, error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotNumeric indicates the input is not a numeric type ErrNotNumeric = errors.New("input is not numeric") // ErrInvalidTimeFormat indicates the input has an invalid time format ErrInvalidTimeFormat = errors.New("input has an invalid time format") // ErrUnsupportedType indicates the input is of an unsupported type ErrUnsupportedType = errors.New("input is of an unsupported type") // ErrNotSlice indicates the expected input should be a slice ErrNotSlice = errors.New("expected input to be a slice") // ErrEmptySlice indicates the slice is empty ErrEmptySlice = errors.New("slice is empty") // ErrInvalidArguments indicates invalid number of arguments ErrInvalidArguments = errors.New("invalid number of arguments") // ErrKeyNotFound indicates the key was not found ErrKeyNotFound = errors.New("key not found") // ErrIndexOutOfRange indicates the index is out of range ErrIndexOutOfRange = errors.New("index out of range") // ErrInvalidKeyType indicates an invalid key type ErrInvalidKeyType = errors.New("invalid key type") // ErrDivisionByZero indicates division by zero ErrDivisionByZero = errors.New("division by zero") // ErrModulusByZero indicates modulus by zero ErrModulusByZero = errors.New("modulus by zero") // ErrUnsupportedSizeType indicates the input type is not supported by the size filter ErrUnsupportedSizeType = errors.New("size filter expects a slice, array, or map") // ErrNegativeValue indicates the input must be non-negative ErrNegativeValue = errors.New("input must be non-negative") )
Functions ¶
func Abs ¶
Abs returns the absolute value of the input.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
result, _ := filter.Abs(-5)
fmt.Println(result)
}
Output: 5
func Base64Decode ¶ added in v0.4.15
Base64Decode decodes a standard Base64 string.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
result, _ := filter.Base64Decode("aGVsbG8gd29ybGQ=")
fmt.Println(result)
}
Output: hello world
func Base64Encode ¶ added in v0.4.15
Base64Encode encodes a string to standard Base64.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.Base64Encode("hello world"))
}
Output: aGVsbG8gd29ybGQ=
func Camelize ¶
Camelize converts a string to camelCase. It lowercases the first letter of the first segment and capitalizes the first letter of each subsequent segment.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.Camelize("hello_world"))
fmt.Println(filter.Camelize("foo-bar-baz"))
}
Output: helloWorld fooBarBaz
func Capitalize ¶
Capitalize capitalizes the first letter and lowercases the rest. This matches Liquid's capitalize behavior.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.Capitalize("hELLO"))
fmt.Println(filter.Capitalize("hello world"))
}
Output: Hello Hello world
func Compact ¶ added in v0.4.15
Compact removes nil elements from a slice. If key is provided, removes elements where the property is nil.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
result, _ := filter.Compact([]any{"a", nil, "b", nil, "c"})
fmt.Println(result)
}
Output: [a b c]
func Concat ¶ added in v0.4.15
Concat combines two slices into one.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
result, _ := filter.Concat([]any{"a", "b"}, []any{"c", "d"})
fmt.Println(result)
}
Output: [a b c d]
func Dasherize ¶
Dasherize converts a string to a lowercased, dashed string, removing non-alphanumeric characters.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.Dasherize("helloWorld"))
fmt.Println(filter.Dasherize("FooBar"))
}
Output: hello-world foo-bar
func Date ¶
Date formats a timestamp into a specified format. Returns a string representation of the date.
func Default ¶
Default returns defaultValue if input is nil, false, or empty string.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.Default("", "fallback"))
fmt.Println(filter.Default("value", "fallback"))
fmt.Println(filter.Default(nil, "fallback"))
fmt.Println(filter.Default(false, "fallback"))
}
Output: fallback value fallback fallback
func Escape ¶ added in v0.4.15
Escape converts <, >, &, ", ' to HTML entities.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.Escape("<p>Hello & World</p>"))
}
Output: <p>Hello & World</p>
func EscapeOnce ¶ added in v0.4.15
EscapeOnce converts <, >, &, ", ' to HTML entities without double-escaping. Already escaped entities like & < ' are preserved.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.EscapeOnce("<p>already escaped</p>"))
fmt.Println(filter.EscapeOnce("1 < 2 & 3"))
}
Output: <p>already escaped</p> 1 < 2 & 3
func Extract ¶
Extract retrieves a value from input using dot-separated key notation. It supports maps, slices, arrays, structs, pointers, and interfaces.
The key uses dot notation for nested access:
- "user.name" accesses the "name" field of "user"
- "items.0.title" accesses the "title" field of the first item
- "matrix.1.0" accesses element [1][0] of a 2D array
Supported input types:
- map[string]interface{} and similar map types
- []interface{} and other slice types
- Arrays (including multi-dimensional)
- Structs with json tags or exported field names
- Pointers to any of the above
- Interfaces containing any of the above
Returns ErrUnsupportedType if input is nil. Returns ErrKeyNotFound if the key path doesn't exist. Returns ErrIndexOutOfRange for invalid array/slice indices. Returns ErrInvalidKeyType for invalid path navigation.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
data := map[string]any{
"user": map[string]any{
"name": "Alice",
"age": 30,
},
}
name, _ := filter.Extract(data, "user.name")
fmt.Println(name)
}
Output: Alice
func Find ¶ added in v0.4.15
Find returns the first element in a slice where the given property equals the given value.
func FindIndex ¶ added in v0.4.15
FindIndex returns the 0-based index of the first element where the given property equals the given value. Returns -1 if not found.
func Has ¶ added in v0.4.15
Has returns true if any element in the slice has a property matching the given criteria. If value is provided, checks property == value. If value is omitted, checks property is truthy.
func Join ¶
Join joins the elements of a slice into a single string with a given separator.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
result, _ := filter.Join([]string{"a", "b", "c"}, ", ")
fmt.Println(result)
}
Output: a, b, c
func Map ¶
Map returns a slice of values for a specified key from each map in the input slice. If the key does not exist in an item, the corresponding value in the result slice will be nil.
func Ordinalize ¶
Ordinalize converts a numeric input to its ordinal English version as a string.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.Ordinalize(1))
fmt.Println(filter.Ordinalize(2))
fmt.Println(filter.Ordinalize(3))
fmt.Println(filter.Ordinalize(11))
}
Output: 1st 2nd 3rd 11th
func Pascalize ¶
Pascalize converts a string to PascalCase, capitalizing the first letter of each segment.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.Pascalize("hello_world"))
fmt.Println(filter.Pascalize("foo-bar"))
}
Output: HelloWorld FooBar
func Pluralize ¶
Pluralize returns the singular or plural form of a string based on count. If the form string contains "%d", the count is substituted into the result. Otherwise, only the appropriate form string is returned without the count.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.Pluralize(1, "item", "items"))
fmt.Println(filter.Pluralize(5, "item", "items"))
}
Output: item items
func Reject ¶ added in v0.4.15
Reject filters a slice, removing elements where the given property equals the given value. If value is omitted, removes elements where the property is truthy. Inverse of Where.
func RemoveFirst ¶ added in v0.4.15
RemoveFirst removes the first occurrence of a substring.
func RemoveLast ¶ added in v0.4.15
RemoveLast removes the last occurrence of a substring.
func Replace ¶
Replace replaces all occurrences of a substring with another string in the input string.
func ReplaceFirst ¶ added in v0.4.15
ReplaceFirst replaces the first occurrence of old with replacement.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.ReplaceFirst("hello hello hello", "hello", "hi"))
}
Output: hi hello hello
func ReplaceLast ¶ added in v0.4.15
ReplaceLast replaces the last occurrence of old with replacement.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.ReplaceLast("hello hello hello", "hello", "hi"))
}
Output: hello hello hi
func Round ¶
Round rounds the input to the specified number of decimal places.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
result, _ := filter.Round(3.14159, 2)
fmt.Println(result)
}
Output: 3.14
func Size ¶
Size returns the length of a collection (slice, array, or map). For string length, use Length instead.
func Slice ¶ added in v0.4.15
Slice extracts a substring or sub-slice. For strings: returns substring starting at offset with optional length. For slices: returns sub-slice starting at offset with optional length. Negative offset counts from end (-1 = last element). If length is omitted, returns single character/element.
func Slugify ¶
Slugify converts a string into a URL-friendly "slug", transliterating Unicode characters to ASCII and replacing or removing special characters.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
result := filter.Slugify("Hello World!")
fmt.Println(result)
}
Output: hello-world
func Sort ¶ added in v0.4.15
Sort sorts a slice in ascending order. If key is provided, sorts slice of maps/structs by that property. Elements whose key cannot be extracted retain their relative order.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
result, _ := filter.Sort([]any{"banana", "apple", "cherry"})
fmt.Println(result)
}
Output: [apple banana cherry]
func SortNatural ¶ added in v0.4.15
SortNatural sorts a slice case-insensitively. If key is provided, sorts by that property case-insensitively. Elements whose key cannot be extracted retain their relative order.
func StripHTML ¶ added in v0.4.15
StripHTML removes all HTML tags, script blocks, style blocks, and comments from the input.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.StripHTML("<p>Hello <b>World</b></p>"))
}
Output: Hello World
func StripNewlines ¶ added in v0.4.15
StripNewlines removes all newline characters (\n, \r\n, \r) from the input.
func TimeAgo ¶
TimeAgo returns a human-readable string representing the time difference between the current time and the input date.
func Trim ¶
Trim strips leading and trailing whitespace from a string.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
result := filter.Trim(" hello ")
fmt.Println(result)
}
Output: hello
func TrimLeft ¶ added in v0.4.15
TrimLeft removes leading whitespace from a string. Liquid equivalent: lstrip.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.TrimLeft(" hello "))
}
Output: hello
func TrimRight ¶ added in v0.4.15
TrimRight removes trailing whitespace from a string. Liquid equivalent: rstrip.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.TrimRight(" hello "))
}
Output: hello
func Truncate ¶
Truncate truncates a string to maxLength characters (including ellipsis). An optional ellipsis string can be provided (default "...").
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.Truncate("Hello, World!", 8))
fmt.Println(filter.Truncate("Hi", 5))
fmt.Println(filter.Truncate("Hello, World!", 10, "--"))
}
Output: Hello... Hi Hello, W--
func TruncateWords ¶
TruncateWords truncates a string to a specified number of words. An optional ellipsis string can be provided (default "...").
func URLEncode ¶ added in v0.4.15
URLEncode percent-encodes a string for use in URLs.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
fmt.Println(filter.URLEncode("hello world"))
}
Output: hello+world
func Unique ¶
Unique removes duplicate elements from a slice. It uses a comparable map for comparable types (fast path) and falls back to hash-based deduplication for non-comparable types like slices and maps.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
result, _ := filter.Unique([]any{1, 2, 2, 3, 3, 3})
fmt.Println(result)
}
Output: [1 2 3]
func Where ¶ added in v0.4.15
Where filters a slice, keeping elements where the given property equals the given value. If value is omitted, keeps elements where the property is truthy.
Example ¶
package main
import (
"fmt"
"github.com/kaptinlin/filter"
)
func main() {
products := []any{
map[string]any{"name": "Shoes", "available": true},
map[string]any{"name": "Shirt", "available": false},
map[string]any{"name": "Pants", "available": true},
}
result, _ := filter.Where(products, "available", true)
for _, p := range result {
m := p.(map[string]any)
fmt.Println(m["name"])
}
}
Output: Shoes Pants
Types ¶
This section is empty.