mirror of
https://github.com/docker/docs.git
synced 2026-10-28 07:15:09 +03:00
Provide basic string manupilation functions for template executions.
This change centralizes the template manipulation in a single package and adds basic string functions to their execution. Signed-off-by: David Calavera <david.calavera@gmail.com>
This commit is contained in:
33
utils/templates/templates.go
Normal file
33
utils/templates/templates.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package templates
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
// basicFunctions are the set of initial
|
||||
// functions provided to every template.
|
||||
var basicFunctions = template.FuncMap{
|
||||
"json": func(v interface{}) string {
|
||||
a, _ := json.Marshal(v)
|
||||
return string(a)
|
||||
},
|
||||
"split": strings.Split,
|
||||
"join": strings.Join,
|
||||
"title": strings.Title,
|
||||
"lower": strings.ToLower,
|
||||
"upper": strings.ToUpper,
|
||||
}
|
||||
|
||||
// Parse creates a new annonymous template with the basic functions
|
||||
// and parses the given format.
|
||||
func Parse(format string) (*template.Template, error) {
|
||||
return NewParse("", format)
|
||||
}
|
||||
|
||||
// NewParse creates a new tagged template with the basic functions
|
||||
// and parses the given format.
|
||||
func NewParse(tag, format string) (*template.Template, error) {
|
||||
return template.New(tag).Funcs(basicFunctions).Parse(format)
|
||||
}
|
||||
38
utils/templates/templates_test.go
Normal file
38
utils/templates/templates_test.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package templates
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseStringFunctions(t *testing.T) {
|
||||
tm, err := Parse(`{{join (split . ":") "/"}}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var b bytes.Buffer
|
||||
if err := tm.Execute(&b, "text:with:colon"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "text/with/colon"
|
||||
if b.String() != want {
|
||||
t.Fatalf("expected %s, got %s", want, b.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewParse(t *testing.T) {
|
||||
tm, err := NewParse("foo", "this is a {{ . }}")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var b bytes.Buffer
|
||||
if err := tm.Execute(&b, "string"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "this is a string"
|
||||
if b.String() != want {
|
||||
t.Fatalf("expected %s, got %s", want, b.String())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user