tplfunc

package
v1.22.13 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2025 License: Apache-2.0 Imports: 16 Imported by: 130

Documentation

Index

Constants

View Source
const (
	EmptyString = ``
)

Variables

View Source
var (
	HashSalt          = time.Now().Format(time.RFC3339)
	HashClipPositions = []uint{1, 3, 8, 9}
	NumberFormat      = com.NumberFormat
)
View Source
var TplFuncMap template.FuncMap = template.FuncMap{}/* 129 elements not displayed */

Functions

func Add

func Add(left interface{}, right interface{}) interface{}

Add returns the sum of two numeric values (int64 or float64) after converting them to compatible types. It handles mixed type inputs by converting both values to float64 if either is not an integer. left: first value to add (int64 or float64) right: second value to add (int64 or float64) Returns: sum of left and right as int64 if both are integers, otherwise float64

func AddSuffix

func AddSuffix(s string, suffix string, args ...string) string

AddSuffix adds the given suffix to the string before the last occurrence of the specified character. If no character is specified, it defaults to '.'. If the character is empty or not found in the string, it simply appends the suffix to the end. Additional args can be provided to specify the character before which to add the suffix.

func AddURLValues added in v1.6.0

func AddURLValues(v url.Values, values ...interface{}) url.Values

AddURLValues adds key-value pairs from the values slice to the url.Values. The values slice should contain alternating keys and values (key1, value1, key2, value2, ...). If an odd number of arguments is provided, the last key will be added with an empty value. Returns the modified url.Values.

func Append

func Append(renderArgs map[string]interface{}, key string, value interface{}) string

Append adds a value to a slice in the renderArgs map under the specified key. If the key doesn't exist, it creates a new slice with the value. Returns EmptyString as a placeholder (no meaningful return value).

func Base64Decode added in v1.3.5

func Base64Decode(s string) string

Base64Decode decodes a base64 encoded string and returns the result. If decoding fails, it logs the error and returns an empty string.

func CaptchaForm

func CaptchaForm(args ...interface{}) template.HTML

CaptchaForm 验证码表单域

func CaptchaFormWithURLPrefix added in v1.4.3

func CaptchaFormWithURLPrefix(urlPrefix string, args ...interface{}) template.HTML

CaptchaFormWithURLPrefix 验证码表单域

func CaptchaVerify

func CaptchaVerify(captchaSolution string, idGet func(string, ...string) string) bool

CaptchaVerify 验证码验证

func Concat

func Concat(s ...string) string

Concat joins multiple strings together without any separator. It takes a variadic number of string arguments and returns their concatenation.

func Default

func Default(defaultV interface{}, v interface{}) interface{}

Default returns defaultV if v is nil, empty, zero or converts to an empty string. Otherwise, it returns v. It handles various primitive types including strings, numeric types (int, float), and converts other types to string for empty check.

func DelimLeft added in v1.6.0

func DelimLeft() string

DelimLeft returns the left delimiter used in templates.

func DelimRight added in v1.6.0

func DelimRight() string

DelimRight returns the right delimiter used in templates.

func Div added in v1.3.0

func Div(left interface{}, right interface{}) interface{}

Div returns the division result of left divided by right after converting both to float64.

func DurationFormat added in v1.3.5

func DurationFormat(lang interface{}, t interface{}, args ...string) *com.Durafmt

DurationFormat converts the given time duration to a formatted string representation based on the specified language. The 't' parameter can be a time.Duration, string, or numeric value representing duration. The 'lang' parameter specifies the language for formatting (e.g., "en" for English). Optional 'args' can provide additional formatting parameters. Returns a pointer to com.Durafmt containing the formatted duration.

func Eq

func Eq(left interface{}, right interface{}) bool

Eq compares two values for equality, handling nil cases properly. Returns true if both values are nil or their string representations are equal.

func FriendlyTime

func FriendlyTime(t interface{}, args ...interface{}) string

FriendlyTime converts various time representations to a human-friendly duration string. It accepts time.Duration, int, int64, uint, int32, uint32, uint64, or any type that can be converted to int64. The optional args parameter allows for customizing the output format. Returns a formatted string representation of the duration.

func Hash added in v1.3.5

func Hash(text, salt string, positions ...uint) string

Hash generates a hashed string from the given text using the provided salt and positions. If salt is empty, it uses the default HashSalt. If no positions are provided, it uses the default HashClipPositions. The resulting hash is created using com.MakePassword with the specified parameters.

func If added in v1.8.5

func If(condition bool, yesValue interface{}, noValue interface{}) interface{}

If returns yesValue if condition is true, otherwise returns noValue.

func Ignore added in v1.3.0

func Ignore(_ interface{}) interface{}

Ignore returns nil for any input value, effectively ignoring it.

func InExt

func InExt(fileName string, exts ...string) bool

InExt checks if the file extension of fileName matches any of the provided extensions (case-insensitive). fileName: The filename to check exts: List of extensions to match against (e.g. ".jpg", ".png") Returns true if the file extension matches any of the provided extensions, false otherwise

func InStrSlice

func InStrSlice(values []string, value string) bool

InStrSlice checks if a string value exists in a string slice. Returns true if the value is found, false otherwise.

func IsEmpty

func IsEmpty(a interface{}) bool

IsEmpty checks if the given interface value is empty. It returns true for nil, empty string, empty slice, or when the string representation is "<nil>", "", or "[]".

func IsInf added in v1.3.0

func IsInf(v interface{}, s interface{}) bool

IsInf reports whether v is an infinity according to s. v is converted to float64 and s is converted to int before comparison. Returns true if v is positive or negative infinity.

func IsNaN added in v1.3.0

func IsNaN(v interface{}) bool

IsNaN reports whether v is a NaN (Not a Number) value after converting it to float64.

func IsNil

func IsNil(a interface{}) bool

IsNil checks if the given interface value is nil. Returns true if the value is nil, false otherwise.

func JSONDecode added in v1.3.5

func JSONDecode(s string) map[string]interface{}

JSONDecode decodes a JSON string into a map[string]interface{}. If decoding fails, it logs the error and returns an empty map.

func JSONDecodeSlice added in v1.12.7

func JSONDecodeSlice(s string) []interface{}

JSONDecodeSlice decodes a JSON string into a slice of interfaces. If decoding fails, logs the error and returns an empty slice.

func JSONEncode added in v1.3.5

func JSONEncode(s interface{}, indents ...string) string

JSONEncode encodes the given value to a JSON string with optional indentation. It returns the JSON string representation of the value. The indents parameter specifies the indentation string to use (e.g., " " for two spaces).

func MakeMap added in v1.6.0

func MakeMap(values ...interface{}) param.Store

MakeMap creates a param.Store from alternating key-value pairs. It accepts either a flat list of arguments or a single slice of values. Keys are converted to strings using fmt.Sprint. If an odd number of arguments is provided, the last key will be set with a nil value.

func MakeSlice added in v1.6.0

func MakeSlice(values ...interface{}) iSlice

MakeSlice converts variadic arguments into an iSlice type.

func Math added in v1.3.0

func Math(op string, args ...interface{}) interface{}

Math performs various mathematical operations based on the given operation string. Supported operations: mod, abs, acos, acosh, asin, asinh, atan, atan2, atanh, cbrt, ceil, copysign, cos, cosh, dim, erf, erfc, exp, exp2, floor, max, min, pow, sqrt, sin, log, log2, log10, tan, tanh, add, sub, mul, div. Returns the result as interface{} which can be converted to appropriate numeric type. Returns 0 if insufficient arguments are provided for the operation.

func Mul added in v1.3.0

func Mul(left interface{}, right interface{}) interface{}

Mul returns the product of two values after converting them to float64. left: the first value to multiply right: the second value to multiply

func New

func New() (r template.FuncMap)

New creates and returns a new template.FuncMap initialized with all functions from TplFuncMap. The returned FuncMap can be used to register template functions.

func Nl2br

func Nl2br(text string) string

Nl2br 将换行符替换为<br />

func NlToBr

func NlToBr(text string) template.HTML

NlToBr Replaces newlines with <br />

func NotEmpty

func NotEmpty(a interface{}) bool

NotEmpty reports whether the given value is not empty. It returns the inverse of IsEmpty(a).

func Now

func Now() time.Time

Now returns the current local time.

func NumberMore added in v1.15.1

func NumberMore(max interface{}, n interface{}) interface{}

NumberMore compares the input number n with max value and returns max+"+" if n is greater than max, otherwise returns n. Supports uint, uint32, uint64, int, int32, int64, float32 and float64 types.

func NumberTrim added in v1.4.3

func NumberTrim(number interface{}, precision int, separator ...string) string

NumberTrim converts a number to float64, truncates it to the specified precision, and formats it with optional separator. Returns the formatted string representation.

Parameters:

  • number: the input number to be formatted (can be any numeric type)
  • precision: the number of decimal places to keep
  • separator: optional thousand separator (default is none)

Returns: formatted string representation of the number

func RandomString added in v1.22.10

func RandomString(length ...uint) string

RandomString generates a random alphanumeric string of specified length. If no length is provided, it defaults to 8 characters.

func SafeBase64Decode added in v1.3.5

func SafeBase64Decode(s string) string

SafeBase64Decode decodes a base64 encoded string safely, returning the decoded string. If decoding fails, it logs the error and returns an empty string.

func SearchStrSlice

func SearchStrSlice(values []string, value string) int

SearchStrSlice searches for the given value in a string slice and returns its index. Returns -1 if the value is not found.

func Set

func Set(renderArgs map[string]interface{}, key string, value interface{}) string

Set adds or updates a key-value pair in the renderArgs map and returns an empty string.

func StrToSlice added in v1.3.5

func StrToSlice(s string, sep string) []interface{}

StrToSlice converts a string into a slice of interfaces by splitting it with the specified separator. Each substring becomes an element in the returned slice.

func Sub

func Sub(left interface{}, right interface{}) interface{}

Sub returns the result of subtracting right from left. It supports both integer and floating-point numbers by automatically converting the inputs to the appropriate numeric type. If either operand is a float, the result will be a float; otherwise, it returns an integer result.

func TemplateTag added in v1.6.0

func TemplateTag(name string) string

TemplateTag returns a template tag string by combining the given name with delimiters.

func TimestampToTime added in v1.2.0

func TimestampToTime(timestamp interface{}) time.Time

TimestampToTime converts various timestamp formats to time.Time. It accepts int, uint, int64, uint64, int32, uint32 or string representations of timestamps. For string inputs, it attempts to parse them as base-10 integers. Returns the corresponding time.Time value or zero time if parsing fails.

func ToCSS

func ToCSS(raw interface{}) template.CSS

ToCSS converts various input types to template.CSS type. It handles conversion from template.HTML, template.CSS, string, and other types (using com.String for conversion). The function ensures the output is always of type template.CSS for safe HTML/CSS rendering.

func ToDecimal added in v1.4.3

func ToDecimal(number interface{}) decimal.Decimal

ToDecimal converts any numeric type to a decimal.Decimal. It first converts the input to float64 using ToFloat64, then creates a decimal from the float value.

func ToDuration added in v1.3.5

func ToDuration(t interface{}, args ...string) time.Duration

ToDuration converts various input types to time.Duration with optional unit specification. Accepts numeric types (int, int64, uint, etc.) and time.Duration as input. Optional args[0] specifies the unit: "ns", "us", "ms", "s", "m", "h" (default: "s"). Returns the converted duration value.

func ToFixed added in v1.3.0

func ToFixed(value interface{}, precision interface{}) string

ToFixed converts a value to a fixed-point string representation with specified precision. value: the input value to convert (can be any numeric type or string representation of a number) precision: the number of decimal places to round to (must be convertible to int)

func ToFloat64 added in v1.3.0

func ToFloat64(value interface{}) float64

ToFloat64 converts the given value to float64. It first attempts to convert to int64, then to float64, and finally falls back to a general conversion if the previous attempts fail.

func ToHTML

func ToHTML(raw interface{}) template.HTML

ToHTML converts raw value to template.HTML type. If input is already template.HTML, returns it directly. For strings, converts to template.HTML without escaping. For other types, converts to string first using com.String.

func ToHTMLAttr

func ToHTMLAttr(raw interface{}) template.HTMLAttr

ToHTMLAttr converts various input types to template.HTMLAttr. It accepts template.HTML, template.HTMLAttr, string, or any type that can be converted to string. Returns the input as template.HTMLAttr, converting non-string types using com.String.

func ToHTMLAttrs

func ToHTMLAttrs(raw map[string]interface{}) (r map[template.HTMLAttr]interface{})

ToHTMLAttrs converts a map of string keys to interface values into a map of HTMLAttr keys. The keys are converted using ToHTMLAttr function while preserving the original values.

func ToJS

func ToJS(raw interface{}) template.JS

ToJS converts various input types to template.JS type for safe JavaScript embedding. It handles template.HTML, template.JS, string, and other types (converted via com.String). The conversion ensures the output is properly escaped for JavaScript contexts.

func ToSlice added in v1.1.1

func ToSlice(s ...interface{}) []interface{}

ToSlice converts variadic arguments into a slice of interfaces.

func ToStrSlice

func ToStrSlice(s ...string) []string

ToStrSlice converts variadic string arguments into a string slice.

func ToTime added in v1.4.3

func ToTime(t interface{}) time.Time

ToTime converts various input types to time.Time. Supports time.Time, string (format: "2006-01-02 15:04:05"), and other types via TsToTime. Panics if string parsing fails.

func ToURL

func ToURL(raw interface{}) template.URL

ToURL converts various input types to template.URL type. It handles conversion from template.HTML, template.URL, string, and other types (using com.String). Returns the converted template.URL value.

func Trim added in v1.10.9

func Trim(s string, cutset ...string) string

Trim removes leading and trailing whitespace from the string s if no cutset is provided. If cutset is provided, it removes all leading and trailing characters contained in the first string of cutset. The function returns the trimmed string.

func TsToDate added in v1.2.0

func TsToDate(format string, timestamp interface{}) string

TsToDate converts a timestamp to a formatted date string. The format parameter follows the standard Go time format layout. If the timestamp is invalid or zero, returns an empty string.

func TsToTime added in v1.2.0

func TsToTime(timestamp interface{}) time.Time

TsToTime converts a timestamp of various types to time.Time by delegating to TimestampToTime.

func URLDecode added in v1.3.5

func URLDecode(s string) string

URLDecode decodes a URL-encoded string and returns the decoded result. If decoding fails, logs the error and returns the original string.

func URLValues added in v1.1.1

func URLValues(values ...interface{}) url.Values

URLValues creates new url.Values and adds the provided values to it. It accepts variadic arguments of key-value pairs or maps to populate the values. Returns the populated url.Values.

func UnicodeDecode added in v1.3.9

func UnicodeDecode(str string) string

UnicodeDecode converts Unicode escape sequences (like \uXXXX) in the input string to their corresponding Unicode characters. It processes the string sequentially, handling both escaped Unicode sequences and regular characters. Invalid escape sequences are preserved as-is in the output.

func UnixTime added in v1.6.0

func UnixTime() int64

UnixTime returns the current time as Unix timestamp (seconds since epoch)

func Unquote added in v1.3.9

func Unquote(s string) string

Unquote removes the surrounding quotes from a string if present. It handles the string as if it were quoted with HTML entity &quot;.

Types

This section is empty.

Jump to

Keyboard shortcuts

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