From f77a7a805af09848011ab112fb4eecdf68425085 Mon Sep 17 00:00:00 2001 From: Tw Date: Tue, 18 Apr 2017 16:17:30 +0800 Subject: [PATCH] template: support custom functions Signed-off-by: Tw --- caddyhttp/httpserver/context.go | 6 +++++- caddyhttp/templates/templates.go | 3 +++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/caddyhttp/httpserver/context.go b/caddyhttp/httpserver/context.go index 5be092a6..13feedc8 100644 --- a/caddyhttp/httpserver/context.go +++ b/caddyhttp/httpserver/context.go @@ -244,6 +244,9 @@ func (c Context) Markdown(filename string) (string, error) { return string(markdown), nil } +// TemplateFuncs contains user defined functions +var TemplateFuncs = template.FuncMap{} + // ContextInclude opens filename using fs and executes a template with the context ctx. // This does the same thing that Context.Include() does, but with the ability to provide // your own context so that the included files can have access to additional fields your @@ -261,7 +264,8 @@ func ContextInclude(filename string, ctx interface{}, fs http.FileSystem) (strin return "", err } - tpl, err := template.New(filename).Parse(string(body)) + tpl := template.New(filename).Funcs(TemplateFuncs) + tpl, err = tpl.Parse(string(body)) if err != nil { return "", err } diff --git a/caddyhttp/templates/templates.go b/caddyhttp/templates/templates.go index afc6fbe3..01abb821 100644 --- a/caddyhttp/templates/templates.go +++ b/caddyhttp/templates/templates.go @@ -44,6 +44,9 @@ func (t Templates) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error tpl.Delims(rule.Delims[0], rule.Delims[1]) } + // Add custom functions + tpl.Funcs(httpserver.TemplateFuncs) + // Build the template templatePath := filepath.Join(t.Root, fpath) tpl, err := tpl.ParseFiles(templatePath)