Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions context/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,18 @@ func (k Context) RunTemplate(t gomplate.Template, env map[string]any) (string, e
} else {
l.V(1).Infof("Running template: %s", t.String())
}
for _, f := range CelEnvFuncs {
t.CelEnvs = append(t.CelEnvs, f(k))
}
if t.Functions == nil {
t.Functions = make(map[string]any)
if t.Expression != "" {
for _, f := range CelEnvFuncs {
t.CelEnvs = append(t.CelEnvs, f(k))
}
}
for name, v := range TemplateFuncs {
t.Functions[name] = v(k)
if t.Template != "" {
if t.Functions == nil {
t.Functions = make(map[string]any)
}
for name, v := range TemplateFuncs {
t.Functions[name] = v(k)
}
}

if t.Template != "" {
Expand Down
41 changes: 41 additions & 0 deletions context/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,50 @@ import (
"testing"

"github.com/flanksource/gomplate/v3"
"github.com/google/cel-go/cel"
. "github.com/onsi/gomega"
)

func TestRunTemplateOnlyBuildsMatchingFunctionContexts(t *testing.T) {
g := NewWithT(t)
oldCelEnvFuncs := CelEnvFuncs
oldTemplateFuncs := TemplateFuncs
defer func() {
CelEnvFuncs = oldCelEnvFuncs
TemplateFuncs = oldTemplateFuncs
}()

var celBuilds int
var templateBuilds int
CelEnvFuncs = map[string]func(Context) cel.EnvOption{
"unused_cel_context": func(ctx Context) cel.EnvOption {
celBuilds++
return cel.Variable("unused_cel_context", cel.AnyType)
},
}
TemplateFuncs = map[string]func(Context) any{
"unused_template_context": func(ctx Context) any {
templateBuilds++
return func() string { return "unused" }
},
}

ctx := New()
env := map[string]any{"name": "World"}

got, err := ctx.RunTemplate(gomplate.Template{Template: "Hello {{.name}}!"}, env)
g.Expect(err).NotTo(HaveOccurred())
g.Expect(got).To(Equal("Hello World!"))
g.Expect(celBuilds).To(Equal(0))
g.Expect(templateBuilds).To(Equal(1))

ok, err := ctx.RunTemplateBool(gomplate.Template{Expression: `name == "World"`}, env)
g.Expect(err).NotTo(HaveOccurred())
g.Expect(ok).To(BeTrue())
g.Expect(celBuilds).To(Equal(1))
g.Expect(templateBuilds).To(Equal(1))
}

func TestRunTemplate(t *testing.T) {
t.Parallel()

Expand Down
Loading