EN IT
Open2b version 7.8

Functions

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).

crypto

encoding

html

math

net

regexp

sort

strconv

strings

time

unsafeconv

The unsafeconv package provides several functions to perform unsafe conversions from strings to other native types.

other functions

crypto

hmacSHA1

func hmacSHA1(message, key string) string

Returns the HMAC encoding, using the SHA1 algorithm, of message with key as the key.

hmacSHA256

func hmacSHA256(message, key string) string

Returns the HMAC encoding, using the hmacSHA256 algorithm, of message with key as the key.

sha1

func sha1(s string) string

Returns the SHA1 hash of s.

sha256

func sha256(s string) string

Returns the SHA256 hash of s.

encoding

base64

func base64(s string) string

Encodes s in Base64.

hex

func hex(s string) string

Returns the hexadecimal encoding of the string s.

marshalJSON

func marshalJSON(v interface{}) (json, error)

Encodes v in JSON format. For details, see the documentation of json.Marshal in the Go standard library.

marshalJSONIndent

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'.

md5

func md5(s string) string

Returns the MD5 hash of the string s.

unmarshalJSON

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.

html

htmlEscape

func htmlEscape(s string) html

Escapes s and returns a value of type html where HTML special characters are replaced, such as "<" with "&lt;".

math

abs

func abs(x int) int

Returns the absolute value of x.

decimal

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.

max

func max(x, y int) int

Returns the maximum of x and y.

min

func min(x, y int) int

Returns the minimum of x and y.

parseDecimal

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.

pow

func pow(x, y float64) float64

Returns x raised to the power of y. For details, see math.Pow in the Go standard library.

net

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.

Example

{% var value, ok = cookie("choice") %}
{% if ok %}
  the cookie value is {{ value }}
{% else %}
  the cookie does not exist
{% end %}

isMailAddress

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.

sendMail

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.

Example

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:

Email sending limits

The following limits apply to sendMail:

If the maximum number of sendable emails is not sufficient, contact us.

queryEscape

func queryEscape(s string) string

Escapes s and returns a new string where special characters in query string values are replaced.

setCookie

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.

regexp

regexp

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.

sort

reverse

func reverse(slice interface{})

Reverses the elements of slice. If slice is not a slice, it fails.

sort

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.

Examples

{% 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

strconv

formatFloat

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.

formatInt

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.

parseFloat

func parseFloat(s string) (float64, error)

Converts the string s to a float64 value.

parseInt

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.

strings

abbreviate

func abbreviate(s string, n int) string

Returns an abbreviated version of s with maximum length n characters.

assetURL

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.

Examples

<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>

capitalize

func capitalize(s string) string

Returns a copy of s with the first letter of the first word capitalized.

capitalizeAll

func capitalizeAll(s string) string

Returns a copy of s with the first letter of each word capitalized.

hasPrefix

func hasPrefix(s, prefix string) bool

Indicates whether the string s has prefix prefix.

hasSuffix

func hasSuffix(s, suffix string) bool

Indicates whether the string s has suffix suffix.

index

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.

indexAny

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.

join

func join(a []string, sep string) string

Concatenates the strings in a using the separator sep.

lastIndex

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.

replace

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

Replaces the first n occurrences of old with new inside s.

replaceAll

func replaceAll(s, old, new string) string

Replaces all occurrences of old with new inside s.

runeCount

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.

split

func split(s, sep string) []string 

Splits s into substrings using sep as the separator.

splitAfter

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>

splitAfterN

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

Like splitN but splits s after the separator sep.

splitN

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

Splits s into substrings using sep as the separator, limiting the number of substrings to n.

sprint

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.

sprintf

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.

toKebab

func toKebab(s string) string

Returns a copy of s in kebab case format.

Example

{{ toKebab("borderTopColor") }}
border-top-color

toLower

func toLower(s string) string

Returns a copy of s with all letters converted to lowercase.

toUpper

func toUpper(s string) string

Returns a copy of s with all letters converted to uppercase.

translate

func translate(key string, args ...interface{}) string

Translates the string corresponding to the given key. The key must be defined in the language files.

trim

func trim(s string, cutset string) string

Returns a copy of s with all leading and trailing Unicode code points contained in cutset removed.

trimLeft

func trimLeft(s string, cutset string) string

Returns a copy of s with all leading Unicode code points contained in cutset removed.

trimPrefix

func trimPrefix(s, prefix string) string

Returns s without the provided prefix string. If s does not start with prefix, it returns s unchanged.

trimRight

func trimRight(s string, cutset string) string

Returns a copy of s with all trailing Unicode code points contained in cutset removed.

trimSuffix

func trimSuffix(s, suffix string) string

Returns s without the provided suffix string. If s does not end with suffix, it returns s unchanged.

time

date

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.

now

func now() Time

Returns the current date and time.

parseDuration

func parseDuration(s string) (Duration, error)

Parses a duration string. For details, see time.ParseDuration in the Go standard library.

parseTime

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.

unixTime

func unixTime(t Time) int

Returns the Unix timestamp of t.

unsafeconv

ToCSS

func ToCSS(s string) css

Converts s to a value of type css.

ToHTML

func ToHTML(s string) html

Converts s to a value of type html.

ToJS

func ToJS(s string) js

Converts s to a value of type js.

ToJSON

func ToJSON(s string) json

Converts s to a value of type json.

ToMarkdown

func ToMarkdown(s string) markdown

Converts s to a value of type markdown.

other functions

len

func len(v interface{}) int

Returns the length of v.

snippet

func snippet(name string) html

Returns the HTML of the snippet with the given name.