diff options
author | kassienull <109551954+kassienull@users.noreply.github.com> | 2023-05-26 12:16:28 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-05-26 10:16:28 -0600 |
commit | 31d75acc9ca5529c300be1ff46ae2dd799fbf9d8 (patch) | |
tree | b2f11bf35905e779cdc608fc4cab8d2de371b73e /modules/caddyhttp/templates/tplcontext.go | |
parent | 9cde71552576dcc724eff38dee42879c927b72ec (diff) |
templates: Add `readFile` action that does not evaluate templates (#5553)
* Create an includeRaw template function to include a file without parsing it as a template.
Some formatting fixes
* Rename to readFile, various docs adjustments
---------
Co-authored-by: Francis Lavoie <lavofr@gmail.com>
Diffstat (limited to 'modules/caddyhttp/templates/tplcontext.go')
-rw-r--r-- | modules/caddyhttp/templates/tplcontext.go | 22 |
1 files changed, 20 insertions, 2 deletions
diff --git a/modules/caddyhttp/templates/tplcontext.go b/modules/caddyhttp/templates/tplcontext.go index fb00f4f..5dc4ae5 100644 --- a/modules/caddyhttp/templates/tplcontext.go +++ b/modules/caddyhttp/templates/tplcontext.go @@ -30,7 +30,7 @@ import ( "time" "github.com/Masterminds/sprig/v3" - "github.com/alecthomas/chroma/v2/formatters/html" + chromahtml "github.com/alecthomas/chroma/v2/formatters/html" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddyhttp" "github.com/dustin/go-humanize" @@ -74,6 +74,7 @@ func (c *TemplateContext) NewTemplate(tplName string) *template.Template { // add our own library c.tpl.Funcs(template.FuncMap{ "include": c.funcInclude, + "readFile": c.funcReadFile, "import": c.funcImport, "httpInclude": c.funcHTTPInclude, "stripHTML": c.funcStripHTML, @@ -123,6 +124,23 @@ func (c TemplateContext) funcInclude(filename string, args ...any) (string, erro return bodyBuf.String(), nil } +// funcReadFile returns the contents of a filename relative to the site root. +// Note that included files are NOT escaped, so you should only include +// trusted files. If it is not trusted, be sure to use escaping functions +// in your template. +func (c TemplateContext) funcReadFile(filename string) (string, error) { + bodyBuf := bufPool.Get().(*bytes.Buffer) + bodyBuf.Reset() + defer bufPool.Put(bodyBuf) + + err := c.readFileToBuffer(filename, bodyBuf) + if err != nil { + return "", err + } + + return bodyBuf.String(), nil +} + // readFileToBuffer reads a file into a buffer func (c TemplateContext) readFileToBuffer(filename string, bodyBuf *bytes.Buffer) error { if c.Root == nil { @@ -315,7 +333,7 @@ func (TemplateContext) funcMarkdown(input any) (string, error) { extension.Footnote, highlighting.NewHighlighting( highlighting.WithFormatOptions( - html.WithClasses(true), + chromahtml.WithClasses(true), ), ), ), |