From 790c842fad876b81d390def66b276cab70568f65 Mon Sep 17 00:00:00 2001 From: Tw Date: Tue, 18 Apr 2017 22:49:20 +0800 Subject: [PATCH] template: add test for custom function Signed-off-by: Tw --- caddyhttp/httpserver/context.go | 3 +-- caddyhttp/httpserver/context_test.go | 8 ++++++++ caddyhttp/templates/templates_test.go | 2 ++ caddyhttp/templates/testdata/root.html | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/caddyhttp/httpserver/context.go b/caddyhttp/httpserver/context.go index 13feedc8..d7d233c5 100644 --- a/caddyhttp/httpserver/context.go +++ b/caddyhttp/httpserver/context.go @@ -264,8 +264,7 @@ func ContextInclude(filename string, ctx interface{}, fs http.FileSystem) (strin return "", err } - tpl := template.New(filename).Funcs(TemplateFuncs) - tpl, err = tpl.Parse(string(body)) + tpl, err := template.New(filename).Funcs(TemplateFuncs).Parse(string(body)) if err != nil { return "", err } diff --git a/caddyhttp/httpserver/context_test.go b/caddyhttp/httpserver/context_test.go index b965e214..50d9c67f 100644 --- a/caddyhttp/httpserver/context_test.go +++ b/caddyhttp/httpserver/context_test.go @@ -72,8 +72,16 @@ func TestInclude(t *testing.T) { shouldErr: true, expectedErrorContent: `type httpserver.Context`, }, + // Test 4 - all good, with custom function + { + fileContent: `hello {{ caddy }}`, + expectedContent: "hello caddy", + shouldErr: false, + expectedErrorContent: "", + }, } + TemplateFuncs["caddy"] = func() string { return "caddy" } for i, test := range tests { testPrefix := getTestPrefix(i) diff --git a/caddyhttp/templates/templates_test.go b/caddyhttp/templates/templates_test.go index 841cf202..f190599c 100644 --- a/caddyhttp/templates/templates_test.go +++ b/caddyhttp/templates/templates_test.go @@ -121,6 +121,8 @@ func TestTemplates(t *testing.T) { rec = httptest.NewRecorder() + // register custom function which is used in template + httpserver.TemplateFuncs["root"] = func() string { return "root" } tmplroot.ServeHTTP(rec, req) if rec.Code != http.StatusOK { diff --git a/caddyhttp/templates/testdata/root.html b/caddyhttp/templates/testdata/root.html index e1720e72..ccc1f634 100644 --- a/caddyhttp/templates/testdata/root.html +++ b/caddyhttp/templates/testdata/root.html @@ -1 +1 @@ -root{{.Include "header.html"}} +{{ root }}{{.Include "header.html"}}