Template Function Injection
This patch enables developers to add one to many template functions that can be used by custom Usage and Help templates. Here is an example that is included in the file cobra_test.go as the test function named TestAddTemplateFunctions: AddTemplateFunc("t", func() bool { return true }) AddTemplateFuncs(template.FuncMap{ "f": func() bool { return false }, "h": func() string { return "Hello," }, "w": func() string { return "world." }}) const usage = "Hello, world." c := &Command{} c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`) if us := c.UsageString(); us != usage { t.Errorf("c.UsageString() != \"%s\", is \"%s\"", usage, us) } In the above example four functions are added to the template function map used when the Usage and Help text is generated from the templates that enable custom logic as well as data injection during template execution.
This commit is contained in:
@ -8,6 +8,7 @@ import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"text/template"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
@ -971,3 +972,20 @@ func TestFlagOnPflagCommandLine(t *testing.T) {
|
||||
|
||||
checkResultContains(t, r, flagName)
|
||||
}
|
||||
|
||||
func TestAddTemplateFunctions(t *testing.T) {
|
||||
AddTemplateFunc("t", func() bool { return true })
|
||||
AddTemplateFuncs(template.FuncMap{
|
||||
"f": func() bool { return false },
|
||||
"h": func() string { return "Hello," },
|
||||
"w": func() string { return "world." }})
|
||||
|
||||
const usage = "Hello, world."
|
||||
|
||||
c := &Command{}
|
||||
c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`)
|
||||
|
||||
if us := c.UsageString(); us != usage {
|
||||
t.Errorf("c.UsageString() != \"%s\", is \"%s\"", usage, us)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user