Go templates#
This page overviews how to use go-lang string-processing sytax - go-templates
. Check description in the official site.
Set up#
Obviously, you need go-lang
to run Go templates, so this notebook requires a specific setup. It uses the gonb kernel to execute the code.
We don’t really need any other go-lang
functions except go-templates
, so the following cell defines a function t
that takes template and prints the result of its execution to the standard output.
package main
import (
"bytes"
"text/template"
"fmt"
)
func t(templateStr string, data ...interface{}) () {
var tmplData interface{}
if len(data) > 0 {
tmplData = data[0]
}
tmpl, _ := template.New("tmpl").Parse(templateStr)
tmpl.Execute(os.Stdout, tmplData)
}
The following cell shows how it can be used. Go templates are typically used to interpret data into a string. The function takes a template and data that need to be displayed using the template.
%%
t("Hello, {{.Name}}!", map[string]string{"Name": "Go"})
Hello, Go!
Access by key#
You can access key-like elements of the data by using the syntax .<key>
.
The following cell extracts val1
and val2
into the template.
%%
t(
"Static text. var1: {{ .val1 }}. var2: {{ .val2 }}",
map[string]string{"val1": "hello", "val2": "world"},
)
Static text. var1: hello. var2: world