Something went wrong. Try again.
Template Tookit - but for Go
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133package gott
import ( "testing")
func TestFunctionInMap(t *testing.T) { renderer, err := New(nil) if err != nil { t.Fatalf("Failed to create renderer: %v", err) }
helpers := map[string]any{ "mytest": func() any { return "string-one" }, "withArgs": func(args ...string) any { return "args:" + args[0] }, "requiresArgs": func(arg string) string { return "got:" + arg }, }
vars := map[string]any{ "h": helpers, }
tests := []struct { name string template string want string }{ { name: "function in map - bareword", template: "[% h.mytest %]", want: "string-one", }, { name: "function in map - explicit call", template: "[% h.mytest() %]", want: "string-one", }, { name: "function with args - explicit call", template: "[% h.withArgs('foo') %]", want: "args:foo", }, { name: "function requiring args - bareword returns empty", template: "[% h.requiresArgs %]", want: "", }, { name: "function requiring args - explicit call", template: "[% h.requiresArgs('bar') %]", want: "got:bar", }, { name: "function in condition", template: "[% IF h.mytest == 'string-one' %]yes[% END %]", want: "yes", }, { name: "function in expression", template: "[% h.mytest %]-suffix", want: "string-one-suffix", }, }
for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := renderer.Process(tt.template, vars) if err != nil { t.Fatalf("Process error: %v", err) } if got != tt.want { t.Errorf("got %q, want %q", got, tt.want) } }) }}
func TestFunctionInNestedMap(t *testing.T) { renderer, err := New(nil) if err != nil { t.Fatalf("Failed to create renderer: %v", err) }
nested := map[string]any{ "nestedFunc": func() any { return "nested-value" }, }
helpers := map[string]any{ "inner": nested, }
vars := map[string]any{ "h": helpers, }
tests := []struct { name string template string want string }{ { name: "nested function - bareword", template: "[% h.inner.nestedFunc %]", want: "nested-value", }, { name: "nested function - explicit call", template: "[% h.inner.nestedFunc() %]", want: "nested-value", }, }
for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := renderer.Process(tt.template, vars) if err != nil { t.Fatalf("Process error: %v", err) } if got != tt.want { t.Errorf("got %q, want %q", got, tt.want) } }) }}