The following are the global functions available in all template pages.
In addition to the functions listed here, templates also have access to Go built-ins (with some exceptions).
func hmacSHA1(message, key string) string
Returns the HMAC encoding, using the SHA1 algorithm, of message with key as the key.
func hmacSHA256(message, key string) string
Returns the HMAC encoding, using the hmacSHA256 algorithm, of message with key as the key.
func sha1(s string) string
Returns the SHA1 hash of s.
func sha256(s string) string
Returns the SHA256 hash of s.
func base64(s string) string
Encodes s in Base64.
func hex(s string) string
Returns the hexadecimal encoding of the string s.
func marshalJSON(v interface{}) (json, error)
Encodes v in JSON format. For details, see the documentation of json.Marshal in the Go standard library.
func marshalJSONIndent(v interface{}, prefix, indent string) (json, error)
Works like marshalJSON, but the output is formatted.
Each element of the generated JSON starts on a new line and begins with prefix followed by one or more copies of indent according to the required indentation.
prefix and indent can contain only whitespace characters: ' ', '\t', '\n' and '\r'.
func md5(s string) string
Returns the MD5 hash of the string s.
func unmarshalJSON(data string, v interface{}) error
Parses the JSON string data and stores the resulting value in the variable pointed to by v.
If v is nil or not a pointer, unmarshalJSON returns an error.
For details, see the documentation of json.Unmarshal in the Go standard library.
func htmlEscape(s string) html
Escapes s and returns a value of type html where HTML special characters are replaced, such as "<" with "<".
func abs(x int) int
Returns the absolute value of x.
func decimal(v Type) Decimal
Returns v as a Decimal value. v can be any integer, float, string, or Decimal. It fails if v is not one of the supported types or if it is a string that does not represent a decimal number.
func max(x, y int) int
Returns the maximum of x and y.
func min(x, y int) int
Returns the minimum of x and y.
func parseDecimal(v interface{}) (Decimal, bool)
Returns v as a Decimal value and true. v can be any integer, float, string, or Decimal. Returns the zero decimal and false if v is not one of the supported types or if it is a string that does not represent a decimal number.
func pow(x, y float64) float64
Returns x raised to the power of y.
For details, see math.Pow in the Go standard library.
func cookie(name string) (string, bool)
Returns the value of the cookie named name and true. If the cookie does not exist it returns an empty string and false.
{% var value, ok = cookie("choice") %}
{% if ok %}
the cookie value is {{ value }}
{% else %}
the cookie does not exist
{% end %}
func isMailAddress(address string) bool
Indicates whether address is an email address accepted by the builtin
sendMail.
Warning: the isMailAddress builtin does not currently implement the
specification faithfully.
In particular, instead of validating the name-addr component of the
email address, the builtin accepts any sequence of characters.
func sendMail(mail Mail) error
Sends the email. If sending fails, either due to invalid fields in
mail or due to a network or internal problem, the function returns a
non-nil error. The email addresses contained in the fields of
mail can be validated with the builtin
isMailAddress before calling
sendMail.
Email can be sent only after CAPTCHA validation. See the following section.
This is an example of a template page for sending email, including CAPTCHA handling code:
{% extends "layouts/standard.html" %}
{% macro Head %}{% end %}
{% Main %}
<form method="POST">
<div class="captcha">{{ captcha }}</div>
<input type="submit" class="design-captcha">
</form>
{%%
submitted := form.Value("g-recaptcha-response") != ""
if submitted {
mail := Mail{
Subject: "Test",
From: "alice@example.com",
To: []string{"bob@example.com"},
Body: "email body",
}
err := sendMail(mail)
if err != nil {
show "Error while sending email: ", err
} else {
show "Email sent correctly"
}
}
%%}
In particular, note:
POST request to the same page<div class="captcha">{{ captcha }}</div> element,
which must be contained inside the formdesign-captchasendMail, wrapped in a condition that checks for the
g-recaptcha-response form value.
The following limits apply to sendMail:
sendMail call can send email to at most 2
To
addresses
sendMail call can send email to at most 2
Cc
addresses
sendMail call can send email to at most 2
Ccn
addresses
If the maximum number of sendable emails is not sufficient, contact us.
func queryEscape(s string) string
Escapes s and returns a new string where special characters in query string values are replaced.
func setCookie(name, value string, maxAge int, httpOnly bool)
Sets a cookie with name name and value value to be returned in the response headers. httpOnly indicates whether the cookie has the "HttpOnly" attribute and maxAge has the following meaning:
If name is not a valid cookie name, setCookie does nothing.
func regexp(expr string) Regexp
Parses the regular expression expr and returns a Regexp value that can be used to search text according to the given expression. It returns an error if expr is not a valid regular expression.
func reverse(slice interface{})
Reverses the elements of slice. If slice is not a slice, it fails.
func sort(slice Type, before func(i, j int) bool)
Sorts the elements of slice. If Slice is not a slice, sort fails.
The before function, if not nil, indicates whether the element with index i should come before the element with index j after sorting. If before is nil, sort sorts the elements using a natural ordering based on their type.
{% var s = []int{3, 5, 2, 9, 7} %}
{% sort(s, nil) %}
{{ sort }}
2 3 5 7 9
{% var s = []int{3, 5, 2, 9, 7} %}
{% var before = func(i, j int) bool { return s[i] > s[j] } %}
{% sort(s, before) %}
{{ s }}
9 7 5 3 2
func formatFloat(f float64, format string, precision int) string
Converts the floating-point number f to a string according to the given format and precision. It may round the result.
The format is one of "e", "f" or "g".
"e": -d.dddde±dd, exponential notation
"f": -ddd.dddd
"g": "e" for large exponents, "f" otherwise.
The precision, which can be between -1 and 1000, indicates the number of decimal digits (excluding the exponent). Precision -1 uses the smallest number of digits such that parseFloat returns exactly f.
For formats "e" and "f" it indicates the number of decimal digits; for format "g" it is the maximum number of significant digits, and trailing zeros are removed.
It panics if the format or precision are invalid.
func formatInt(i int, base int) string
Returns the representation of integer i in the given base, for 2 <= base <= 36. The result uses lowercase letters from 'a' to 'z' for digits with value >= 10.
It panics if base is outside the valid range.
func parseFloat(s string) (float64, error)
Converts the string s to a float64 value.
func parseInt(s string, base int) (int, error)
Parses the string s in the given base, for 2 <= base <= 36, and returns the corresponding value. It returns 0 and an error if s is empty, contains invalid digits, or the value represented by s cannot be represented by an int.
func abbreviate(s string, n int) string
Returns an abbreviated version of s with maximum length n characters.
func assetURL(name string) string
Returns the URL of an asset given its name. Assets are files in the template folder such as CSS files and images. If name is not valid, for example for files with the "html" extension, it returns an empty string.
<img src="{{ assetURL(`/images/picture.png`) }}">
<img src="https://cdn.shop.com/images/picture.png">
<script> var url = {{ assetURL("/images/picture.png") }}; </script>
<script> var url = "https://cdn.shop.com/images/picture.png"; </script>
func capitalize(s string) string
Returns a copy of s with the first letter of the first word capitalized.
func capitalizeAll(s string) string
Returns a copy of s with the first letter of each word capitalized.
func hasPrefix(s, prefix string) bool
Indicates whether the string s has prefix prefix.
func hasSuffix(s, suffix string) bool
Indicates whether the string s has suffix suffix.
func index(s, substr string) int
Returns the index of substr inside s. If substr is not present in s, it returns -1.
As with strings.Index from the Go standard library, the returned index is in bytes, not in characters of s.
func indexAny(s, chars string) int
Returns the index of the first occurrence in s of any character in chars.
As with strings.Index from the Go standard library, the returned index is in bytes, not in characters of s.
func join(a []string, sep string) string
Concatenates the strings in a using the separator sep.
func lastIndex(s, sep string) int
Returns the index of the last occurrence of sep inside s.
As with strings.Index from the Go standard library, the returned index is in bytes, not in characters of s.
func replace(s, old, new string, n int) string
Replaces the first n occurrences of old with new inside s.
func replaceAll(s, old, new string) string
Replaces all occurrences of old with new inside s.
func runeCount(s string) int
Returns the number of runes (Unicode code points) in s. To count the number of “characters” in a string, runeCount is more appropriate because len returns the number of bytes.
func split(s, sep string) []string
Splits s into substrings using sep as the separator.
func splitAfter(s, sep string) []string
Like split but splits s after the separator sep. For example:
{% for s in splitAfter("<section><div>a</div><div>b</div></section>", ">") %}
{{ s }}
{% end %}
<section>
a</div>
<div>
b</div>
</section>
func splitAfterN(s, sep string, n int) []string
Like splitN but splits s after the separator sep.
func splitN(s, sep string, n int) []string
Splits s into substrings using sep as the separator, limiting the number of substrings to n.
func sprint(a ...interface{}) string
Formats the arguments and returns a string. For example:
{% const name, age = "Sherlock Holmes", 60 %}
{{ sprint(name, " is ", age, " years old") }}
Sherlock Holmes is 60 years old
sprint accepts the same arguments and behaves like fmt.Sprint in the Go standard library.
func sprintf(format string, a ...interface{}) string
Formats the arguments according to format and returns a string. For example:
{% const name, age = "Sherlock Holmes", 60 %}
{{ sprintf("%s is %d years old", name, age) }}
Sherlock Holmes is 60 years old
sprintf accepts the same arguments and behaves like fmt.Sprintf in the Go standard library.
func toKebab(s string) string
Returns a copy of s in kebab case format.
{{ toKebab("borderTopColor") }}
border-top-color
func toLower(s string) string
Returns a copy of s with all letters converted to lowercase.
func toUpper(s string) string
Returns a copy of s with all letters converted to uppercase.
func translate(key string, args ...interface{}) string
Translates the string corresponding to the given key. The key must be defined in the language files.
func trim(s string, cutset string) string
Returns a copy of s with all leading and trailing Unicode code points contained in cutset removed.
func trimLeft(s string, cutset string) string
Returns a copy of s with all leading Unicode code points contained in cutset removed.
func trimPrefix(s, prefix string) string
Returns s without the provided prefix string. If s does not start with prefix, it returns s unchanged.
func trimRight(s string, cutset string) string
Returns a copy of s with all trailing Unicode code points contained in cutset removed.
func trimSuffix(s, suffix string) string
Returns s without the provided suffix string. If s does not end with suffix, it returns s unchanged.
func date(format string, time Time) string
Formats the time value using the provided format. For details, see the Go standard library time.Time.Format documentation.
func now() Time
Returns the current date and time.
func parseDuration(s string) (Duration, error)
Parses a duration string. For details, see time.ParseDuration in the Go standard library.
func parseTime(s string, layout string) (Time, error)
Parses a time value using the specified layout. For details, see time.Parse in the Go standard library.
func unixTime(t Time) int
Returns the Unix timestamp of t.
func ToCSS(s string) css
Converts s to a value of type css.
func ToHTML(s string) html
Converts s to a value of type html.
func ToJS(s string) js
Converts s to a value of type js.
func ToJSON(s string) json
Converts s to a value of type json.
func ToMarkdown(s string) markdown
Converts s to a value of type markdown.
func len(v interface{}) int
Returns the length of v.
func snippet(name string) html
Returns the HTML of the snippet with the given name.