From 31d75acc9ca5529c300be1ff46ae2dd799fbf9d8 Mon Sep 17 00:00:00 2001 From: kassienull <109551954+kassienull@users.noreply.github.com> Date: Fri, 26 May 2023 12:16:28 -0400 Subject: 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 --- modules/caddyhttp/templates/tplcontext.go | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) (limited to 'modules/caddyhttp/templates/tplcontext.go') 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), ), ), ), -- cgit v1.2.3