builtin

package
v0.40.0 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2021 License: BSD-3-Clause Imports: 19 Imported by: 0

Documentation

Overview

Package builtin provides simple functions, types and constants that can be used as globals in a Scriggo template.

For example, to use the Min and Max functions as global min and max functions

globals := templates.Declarations{
    "min": builtin.Min,
    "max": builtin.Max,
}
opts := &templates.BuildOptions{
    Globals: globals,
}
template, err := scriggoTemplates.Build(fsys, file, opts)

And to use them in a template

{{ min(x, y) }}
{{ max(x, y) }}

Use the regexp function and the returned Regex value in this way

{% var re = regexp(`(scrig)go`) %}
{{ re.Match("go") }}
{{ re.Match("scriggo") }}

Use this Declarations value to use all the builtin of this package in a template or choose the most appropriate

templates.Declarations{
    "Duration":          reflect.TypeOf((*builtin.Duration)(nil)).Elem(),
    "Hour":              time.Hour,
    "Microsecond":       time.Microsecond,
    "Millisecond":       time.Millisecond,
    "Minute":            time.Minute,
    "Nanosecond":        time.Nanosecond,
    "Regexp":            reflect.TypeOf((*builtin.Regexp)(nil)).Elem(),
    "Second":            time.Second,
    "Time":              reflect.TypeOf((*builtin.Time)(nil)).Elem(),
    "abbreviate":        builtin.Abbreviate,
    "abs":               builtin.Abs,
    "base64":            builtin.Base64,
    "capitalize":        builtin.Capitalize,
    "capitalizeAll":     builtin.CapitalizeAll,
    "date":              builtin.Date,
    "hasPrefix":         builtin.HasPrefix,
    "hasSuffix":         builtin.HasSuffix,
    "hex":               builtin.Hex,
    "hmacSHA1":          builtin.HmacSHA1,
    "hmacSHA256":        builtin.HmacSHA256,
    "htmlEscape":        builtin.HtmlEscape,
    "index":             builtin.Index,
    "indexAny":          builtin.IndexAny,
    "join":              builtin.Join,
    "lastIndex":         builtin.LastIndex,
    "marshalJSON":       builtin.MarshalJSON
    "marshalJSONIndent": builtin.MarshalJSONIndent,
    "max":               builtin.Max,
    "md5":               builtin.Md5,
    "min":               builtin.Min,
    "now":               builtin.Now,
    "parseDuration":     builtin.ParseDuration,
    "parseTime":         builtin.ParseTime,
    "queryEscape":       builtin.QueryEscape,
    "regexp":            builtin.RegExp,
    "replace":           builtin.Replace,
    "replaceAll":        builtin.ReplaceAll,
    "reverse":           builtin.Reverse,
    "runeCount":         builtin.RuneCount,
    "sha1":              builtin.Sha1,
    "sha256":            builtin.Sha256,
    "sort":              builtin.Sort,
    "split":             builtin.Split,
    "splitAfter":        builtin.SplitAfter,
    "splitAfterN":       builtin.SplitAfterN,
    "splitN":            builtin.SplitN,
    "sprint":            builtin.Sprint,
    "sprintf":           builtin.Sprintf,
    "toKebab":           builtin.ToKebab,
    "toLower":           builtin.ToLower,
    "toUpper":           builtin.ToUpper,
    "trim":              builtin.Trim,
    "trimLeft":          builtin.TrimLeft,
    "trimPrefix":        builtin.TrimPrefix,
    "trimRight":         builtin.TrimRight,
    "trimSuffix":        builtin.TrimSuffix,
    "unixTime":          builtin.UnixTime,
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Abbreviate

func Abbreviate(s string, n int) string

Abbreviate abbreviates s to almost n runes. If s is longer than n runes, the abbreviated string terminates with "...".

func Abs

func Abs(x int) int

Abs returns the absolute value of x.

func Base64

func Base64(s string) string

Base64 returns the base64 encoding of s.

func Capitalize

func Capitalize(src string) string

Capitalize returns a copy of the string src with the first non-separator in upper case.

func CapitalizeAll

func CapitalizeAll(src string) string

CapitalizeAll returns a copy of the string src with the first letter of each word in upper case.

func HasPrefix

func HasPrefix(s, prefix string) bool

HasPrefix tests whether the string s begins with prefix.

func HasSuffix

func HasSuffix(s, suffix string) bool

HasSuffix tests whether the string s ends with suffix.

func Hex

func Hex(src string) string

Hex returns the hexadecimal encoding of src.

func HmacSHA1

func HmacSHA1(message, key string) string

HmacSHA1 returns the HMAC-SHA1 tag for the given message and key, as a base64 encoded string.

func HmacSHA256

func HmacSHA256(message, key string) string

HmacSHA256 returns the HMAC-SHA256 tag for the given message and key, as a base64 encoded string.

func HtmlEscape

func HtmlEscape(s string) templates.HTML

HtmlEscape escapes s, replacing the characters <, >, &, " and ' and returns the escaped string as templates.HTML type.

func Index

func Index(s, substr string) int

Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.

func IndexAny

func IndexAny(s, chars string) int

IndexAny returns the index of the first instance of any Unicode code point from chars in s, or -1 if no Unicode code point from chars is present in s.

func Join

func Join(elems []string, sep string) string

Join concatenates the elements of its first argument to create a single string. The separator string sep is placed between elements in the resulting string.

func LastIndex

func LastIndex(s, substr string) int

LastIndex returns the index of the last instance of substr in s, or -1 if substr is not present in s.

func MarshalJSON added in v0.40.0

func MarshalJSON(v interface{}) (templates.JSON, error)

MarshalJSON returns the JSON encoding of v.

See https://golang.org/pkg/encoding/json/#Marshal for details.

func MarshalJSONIndent added in v0.40.0

func MarshalJSONIndent(v interface{}, prefix, indent string) (templates.JSON, error)

MarshalJSONIndent is like MarshalJSON but indents the output. Each JSON element in the output will begin on a new line beginning with prefix followed by one or more copies of indent according to the indentation nesting. prefix and indent can only contain whitespace: ' ', '\t', '\n' and '\r'.

func Max

func Max(x, y int) int

Max returns the larger of x or y.

func Md5

func Md5(src string) string

Md5 returns the MD5 checksum of src as an hexadecimal encoded string.

func Min

func Min(x, y int) int

Min returns the smaller of x or y.

func QueryEscape

func QueryEscape(s string) string

QueryEscape escapes the string so it can be safely placed inside a URL query.

func Replace

func Replace(s, old, new string, n int) string

Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements.

func ReplaceAll

func ReplaceAll(s, old, new string) string

ReplaceAll returns a copy of the string s with all non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string.

func Reverse

func Reverse(data interface{})

Reverse returns the reverse order for data.

func RuneCount

func RuneCount(s string) (n int)

RuneCount returns the number of runes in s. Erroneous and short encodings are treated as single runes of width 1 byte.

func Sha1

func Sha1(src string) string

Sha1 returns the SHA1 checksum of src as an hexadecimal encoded string.

func Sha256

func Sha256(s string) string

Sha256 returns the SHA256 checksum of src as an hexadecimal encoded string.

func Sort

func Sort(slice interface{}, less func(i, j int) bool)

Sort sorts the provided slice given the provided less function.

The function panics if the provided interface is not a slice.

func Split

func Split(s, sep string) []string

Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators.

If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s.

If sep is empty, Split splits after each UTF-8 sequence. If both s and sep are empty, Split returns an empty slice.

It is equivalent to SplitN with a count of -1.

func SplitAfter added in v0.39.0

func SplitAfter(s, sep string) []string

SplitAfter slices s into all substrings after each instance of sep and returns a slice of those substrings.

If s does not contain sep and sep is not empty, SplitAfter returns a slice of length 1 whose only element is s.

If sep is empty, SplitAfter splits after each UTF-8 sequence. If both s and sep are empty, SplitAfter returns an empty slice.

It is equivalent to SplitAfterN with a count of -1.

func SplitAfterN added in v0.39.0

func SplitAfterN(s, sep string, n int) []string

SplitAfterN slices s into substrings after each instance of sep and returns a slice of those substrings.

The count determines the number of substrings to return:

n > 0: at most n substrings; the last substring will be the unsplit remainder.
n == 0: the result is nil (zero substrings)
n < 0: all substrings

Edge cases for s and sep (for example, empty strings) are handled as described in the documentation for SplitAfter.

func SplitN

func SplitN(s, sep string, n int) []string

SplitN slices s into substrings separated by sep and returns a slice of the substrings between those separators.

The count determines the number of substrings to return:

n > 0: at most n substrings; the last substring will be the unsplit remainder.
n == 0: the result is nil (zero substrings)
n < 0: all substrings

Edge cases for s and sep (for example, empty strings) are handled as described in the documentation for Split.

func Sprint

func Sprint(a ...interface{}) string

Sprint formats using the default formats for its operands and returns the resulting string. Spaces are added between operands when neither is a string.

func Sprintf

func Sprintf(format string, a ...interface{}) string

Sprintf formats according to a format specifier and returns the resulting string.

func ToKebab

func ToKebab(s string) string

ToKebab returns a copy of the string s in kebab case form.

func ToLower

func ToLower(s string) string

ToLower returns s with all Unicode letters mapped to their lower case.

func ToUpper

func ToUpper(s string) string

ToUpper returns s with all Unicode letters mapped to their upper case.

func Trim

func Trim(s, cutset string) string

Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.

func TrimLeft

func TrimLeft(s, cutset string) string

TrimLeft returns a slice of the string s with all leading Unicode code points contained in cutset removed.

To remove a prefix, use TrimPrefix instead.

func TrimPrefix

func TrimPrefix(s, prefix string) string

TrimPrefix returns s without the provided leading prefix string. If s doesn't start with prefix, s is returned unchanged.

func TrimRight

func TrimRight(s, cutset string) string

TrimRight returns a slice of the string s, with all trailing Unicode code points contained in cutset removed.

To remove a suffix, use TrimSuffix instead.

func TrimSuffix

func TrimSuffix(s, suffix string) string

TrimSuffix returns s without the provided trailing suffix string. If s doesn't end with suffix, s is returned unchanged.

Types

type Duration added in v0.40.0

type Duration = time.Duration

A Duration represents the elapsed time between two instants as an int64 nanosecond count. The representation limits the largest representable duration to approximately 290 years.

func ParseDuration added in v0.40.0

func ParseDuration(s string) (Duration, error)

ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

type Regexp added in v0.39.0

type Regexp struct {
	// contains filtered or unexported fields
}

Regexp represents a regular expression.

func RegExp added in v0.39.0

func RegExp(env runtime.Env, expr string) Regexp

RegExp parses a regular expression and returns a Regexp object that can be used to match against text. It panics if the expression cannot be parsed.

func (Regexp) Find added in v0.39.0

func (re Regexp) Find(s string) string

Find returns a string holding the text of the leftmost match in s of the regular expression. If there is no match, the return value is an empty string, but it will also be empty if the regular expression successfully matches an empty string. Use FindSubmatch if it is necessary to distinguish these cases.

func (Regexp) FindAll added in v0.39.0

func (re Regexp) FindAll(s string, n int) []string

FindAll is the 'All' version of Find; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the Go regexp package comment. A return value of nil indicates no match.

func (Regexp) FindAllSubmatch added in v0.39.0

func (re Regexp) FindAllSubmatch(s string, n int) [][]string

FindAllSubmatch is the 'All' version of FindSubmatch; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the Go regexp package comment. A return value of nil indicates no match.

func (Regexp) FindSubmatch added in v0.39.0

func (re Regexp) FindSubmatch(s string) []string

FindSubmatch returns a slice of strings holding the text of the leftmost match of the regular expression in s and the matches, if any, of its subexpressions, as defined by the 'Submatch' description in the Go regexp package comment. A return value of nil indicates no match.

func (Regexp) Match added in v0.39.0

func (re Regexp) Match(s string) bool

Match reports whether the string s contains any match of the regular expression.

func (Regexp) ReplaceAll added in v0.39.0

func (re Regexp) ReplaceAll(src, repl string) string

ReplaceAll returns a copy of src, replacing matches of the Regexp with the replacement string repl. Inside repl, $ signs are interpreted as in Expand method of the Go regexp package, so for instance $1 represents the text of the first submatch.

func (Regexp) ReplaceAllFunc added in v0.39.0

func (re Regexp) ReplaceAllFunc(src string, repl func(string) string) string

ReplaceAllFunc returns a copy of src in which all matches of the Regexp have been replaced by the return value of function repl applied to the matched substring. The replacement returned by repl is substituted directly, without expanding.

func (Regexp) Split added in v0.39.0

func (re Regexp) Split(s string, n int) []string

Split slices s into substrings separated by the expression and returns a slice of the substrings between those expression matches.

The slice returned by this method consists of all the substrings of s not contained in the slice returned by FindAllString. When called on an expression that contains no metacharacters, it is equivalent to SplitN.

The count determines the number of substrings to return:

n > 0: at most n substrings; the last substring will be the unsplit remainder.
n == 0: the result is nil (zero substrings)
n < 0: all substrings

type Time added in v0.40.0

type Time struct {
	// contains filtered or unexported fields
}

A Time represents an instant in time.

It is a stripped down version of the Go time.Time type, with additional methods to show time values in JavaScript and JSON contexts.

func Date added in v0.40.0

func Date(year, month, day, hour, min, sec, nsec int, location string) (Time, error)

Date returns the time corresponding to the given date with time zone determined by location. If location does not exist, it returns an error.

For example, the following call returns March 27, 2021 11:21:14.964553705 CET.

Date(2021, 3, 27, 11, 21, 14, 964553705, "Europe/Rome")

For UTC use "" or "UTC" as location. For the system's local time zone use "Local" as location.

The month, day, hour, min, sec and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1.

func NewTime added in v0.40.0

func NewTime(t time.Time) Time

NewTime returns a Time value at the time of t. It is not intended to be used as a builtin but it can be used to implement builtins that return time values.

For example, a builtin that returns the current local time rounded to milliseconds and with location "America/New_York" can be implemented as

func now() builtin.Time {
    l := time.LoadLocation("America/New_York")
    t := time.Now().Rounded(time.Millisecond).In(l)
    return builtin.NewTime(t)
}

and once added to the declarations

templates.Declarations{
    ...
    "now" : now,
    ...
}

it can be used in a template

Current time: {{ now() }}

func Now added in v0.40.0

func Now() Time

Now returns the current local time.

func ParseTime added in v0.40.0

func ParseTime(layout, value string) (Time, error)

ParseTime parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time would be

Mon Jan 2 15:04:05 -0700 MST 2006

would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.

See https://golang.org/pkg/time/#Parse for more details.

As a special case, if layout is an empty string, ParseTime parses a time representation using a predefined list of layouts.

It returns an error if value cannot be parsed.

func UnixTime added in v0.40.0

func UnixTime(sec int64, nsec int64) Time

UnixTime returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC. It is valid to pass nsec outside the range [0, 999999999]. Not all sec values have a corresponding time value. One such value is 1<<63-1 (the largest int64 value).

func (Time) Add added in v0.40.0

func (t Time) Add(d Duration) Time

Add returns the time t+d.

func (Time) AddDate added in v0.40.0

func (t Time) AddDate(years, months, days int) Time

AddDate returns the time corresponding to adding the given number of years, months and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.

AddDate normalizes its result in the same way that the Date function does.

func (Time) After added in v0.40.0

func (t Time) After(u Time) bool

After reports whether the time instant t is after u.

func (Time) Before added in v0.40.0

func (t Time) Before(u Time) bool

Before reports whether the time instant t is before u.

func (Time) Clock added in v0.40.0

func (t Time) Clock() (hour, minute, second int)

Clock returns the hour, minute and second within the day specified by t. hour is in the range [0, 23], minute and second are in the range [0, 59].

func (Time) Date added in v0.40.0

func (t Time) Date() (year, month, day int)

Date returns the year, month and day in which t occurs. month is in the range [1, 12] and day is in the range [1, 31].

func (Time) Day added in v0.40.0

func (t Time) Day() int

Day returns the day of the month specified by t, in the range [1, 31].

func (Time) Equal added in v0.40.0

func (t Time) Equal(u Time) bool

Equal reports whether t and u represent the same time instant.

func (Time) Format added in v0.40.0

func (t Time) Format(layout string) string

Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.

A fractional second is represented by adding a period and zeros to the end of the seconds section of layout string, as in "15:04:05.000" to format a time stamp with millisecond precision.

func (Time) Hour added in v0.40.0

func (t Time) Hour() int

Hour returns the hour within the day specified by t, in the range [0, 23].

func (Time) JS added in v0.40.0

func (t Time) JS() templates.JS

JS returns the time as a JavaScript date. The result is undefined if the year of t is not in the range [-999999, 999999].

func (Time) JSON added in v0.40.0

func (t Time) JSON() templates.JSON

JSON returns a time in a format suitable for use in JSON.

func (Time) Minute added in v0.40.0

func (t Time) Minute() int

Minute returns the minute offset within the hour specified by t, in the range [0, 59].

func (Time) Month added in v0.40.0

func (t Time) Month() int

Month returns the month of the year specified by t, in the range [1, 12] where 1 is January and 12 is December.

func (Time) Nanosecond added in v0.40.0

func (t Time) Nanosecond() int

Nanosecond returns the nanosecond offset within the second specified by t, in the range [0, 999999999].

func (Time) Round added in v0.40.0

func (t Time) Round(d Duration) Time

Round returns the result of rounding t to the nearest multiple of d (since the zero time). The rounding behavior for halfway values is to round up. If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged.

Round operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Round(Hour) may return a time with a non-zero minute, depending on the time's Location.

func (Time) Second added in v0.40.0

func (t Time) Second() int

Second returns the second offset within the minute specified by t, in the range [0, 59].

func (Time) String added in v0.40.0

func (t Time) String() string

String returns the time formatted.

func (Time) Sub added in v0.40.0

func (t Time) Sub(u Time) Duration

Sub returns the duration t-u. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, the maximum (or minimum) duration will be returned. To compute t-d for a duration d, use t.Add(-d).

func (Time) Truncate added in v0.40.0

func (t Time) Truncate(d Duration) Time

Truncate returns the result of rounding t down to a multiple of d (since the zero time). If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged.

Truncate operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Truncate(Hour) may return a time with a non-zero minute, depending on the time's Location.

func (Time) UTC added in v0.40.0

func (t Time) UTC() Time

UTC returns t with the location set to UTC.

func (Time) Unix added in v0.40.0

func (t Time) Unix() int64

Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC. The result does not depend on the location associated with t. Unix-like operating systems often record time as a 32-bit count of seconds, but since the method here returns a 64-bit value it is valid for billions of years into the past or future.

func (Time) UnixNano added in v0.40.0

func (t Time) UnixNano() int64

UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in nanoseconds cannot be represented by an int64 (a date before the year 1678 or after 2262). Note that this means the result of calling UnixNano on the zero Time is undefined. The result does not depend on the location associated with t.

func (Time) Weekday added in v0.40.0

func (t Time) Weekday() int

Weekday returns the day of the week specified by t.

func (Time) Year added in v0.40.0

func (t Time) Year() int

Year returns the year in which t occurs.

func (Time) YearDay added in v0.40.0

func (t Time) YearDay() int

YearDay returns the day of the year specified by t, in the range [1, 365] for non-leap years, and [1, 366] in leap years.

Jump to

Keyboard shortcuts

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