summaryrefslogtreecommitdiff
path: root/modules/caddyhttp/templates/tplcontext.go
diff options
context:
space:
mode:
authorMatthew Holt <mholt@users.noreply.github.com>2019-06-18 15:17:48 -0600
committerMatthew Holt <mholt@users.noreply.github.com>2019-06-18 15:17:48 -0600
commit2663dd176d38dfb929bcc478cac3913827f1246e (patch)
tree2b5da588e9ae5eb2e0e13d223aeda7c0922eed35 /modules/caddyhttp/templates/tplcontext.go
parent6706c9225a8dcb976785bdf2c35eb151d54ac18c (diff)
Refactor templates execution; add sprig functions
Diffstat (limited to 'modules/caddyhttp/templates/tplcontext.go')
-rw-r--r--modules/caddyhttp/templates/tplcontext.go36
1 files changed, 23 insertions, 13 deletions
diff --git a/modules/caddyhttp/templates/tplcontext.go b/modules/caddyhttp/templates/tplcontext.go
index 7123c42..31ef666 100644
--- a/modules/caddyhttp/templates/tplcontext.go
+++ b/modules/caddyhttp/templates/tplcontext.go
@@ -17,6 +17,7 @@ import (
"os"
+ "github.com/Masterminds/sprig"
"github.com/caddyserver/caddy/modules/caddyhttp"
"gopkg.in/russross/blackfriday.v2"
)
@@ -27,7 +28,8 @@ type templateContext struct {
Req *http.Request
Args []interface{} // defined by arguments to .Include
RespHeader tplWrappedHeader
- server http.Handler
+
+ config *Templates
}
// Include returns the contents of filename relative to the site root.
@@ -53,7 +55,12 @@ func (c templateContext) Include(filename string, args ...interface{}) (string,
c.Args = args
- return c.executeTemplate(filename, bodyBuf.Bytes())
+ err = c.executeTemplateInBuffer(filename, bodyBuf)
+ if err != nil {
+ return "", err
+ }
+
+ return bodyBuf.String(), nil
}
// HTTPInclude returns the body of a virtual (lightweight) request
@@ -81,25 +88,28 @@ func (c templateContext) HTTPInclude(uri string) (string, error) {
return "", fmt.Errorf("http %d", vrw.status)
}
- return c.executeTemplate(uri, buf.Bytes())
-}
-
-func (c templateContext) executeTemplate(tplName string, body []byte) (string, error) {
- tpl, err := template.New(tplName).Parse(string(body))
+ err = c.executeTemplateInBuffer(uri, buf)
if err != nil {
return "", err
}
- buf := bufPool.Get().(*bytes.Buffer)
- buf.Reset()
- defer bufPool.Put(buf)
+ return buf.String(), nil
+}
+
+func (c templateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buffer) error {
+ tpl := template.New(tplName).Funcs(sprig.TxtFuncMap())
+ if len(c.config.Delimiters) == 2 {
+ tpl.Delims(c.config.Delimiters[0], c.config.Delimiters[1])
+ }
- err = tpl.Execute(buf, c)
+ parsedTpl, err := tpl.Parse(buf.String())
if err != nil {
- return "", err
+ return err
}
- return buf.String(), nil
+ buf.Reset() // reuse buffer for output
+
+ return parsedTpl.Execute(buf, c)
}
// Now returns the current timestamp.