Template functions

Functions are an important part of the template engine and there are many built-in functions, such as comparison (eq, lt, gt, le, ge) or logical (AND, OR, NOT). Functions are called by their names, followed by arguments using space as separator. The function used in the previous example, lt a b, means lt(a,b). When the functions are more nested, it's required to wrap functions and arguments in parentheses. For instance, the not lt a b statement means that the X function has three arguments, not(lt, a, b). The correct version is not (lt a b), which tells the template that the elements in the parentheses need to be solved first.

When creating a template, custom functions can be assigned to it with the Funcs method and can be used in the template. This is very useful, as we can see in this example:

var data = struct {
Name, Surname, Occupation, City string
}{
"Bojack", "Horseman", "Actor", "Los Angeles",
}
tpl, err := template.New("question-answer").Funcs(template.FuncMap{
"upper": func(s string) string { return strings.ToUpper(s) },
"lower": func(s string) string { return strings.ToLower(s) },
}).Parse(`{{.Name}} {{.Surname}} - {{lower .Occupation}} from {{upper .City}}`)
if err != nil {
log.Fatalln("Error:", err)
}
if err = tpl.Execute(os.Stdout, data); err != nil {
log.Fatalln("Error:", err)
}

The full example is available here: https://play.golang.org/p/DdoKEOixDDB.

The | operator can be used to link the output of a statement to the input of another statement, similar to how it happens in the Unix shell. For instance, the {{"put" | printf "%s%s" "out" | printf "%q"}} statement will produce "output".

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.78.136