@marcel91200 / caddy Mirror · read-only / commits / 2bc30bb7
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 14, 05:15 UTC

templates: Implement placeholders function (#3324)

* caddyhttp, httpcaddyfile: Implement placeholders in template * caddyhttp, httpcaddyfile: Remove support for placeholder shorthands in templates * Update modules/caddyhttp/templates/templates.go updates JSON doc Co-authored-by: Matt Holt <mholt@users.noreply.github.com> * Update modules/caddyhttp/templates/tplcontext.go Co-authored-by: Matt Holt <mholt@users.noreply.github.com> Co-authored-by: Matt Holt <mholt@users.noreply.github.com>

Patrick Hein committed Jul 21, 2020 at 01:17 UTC 2bc30bb780f3b93593a2a9e42db6ab215fe12902
2 files changed +18
modules/caddyhttp/templates/templates.go
+10
@@ -64,6 +64,16 @@ func init() {
64 // {{env "VAR_NAME"}}
65 // ```
66 //
67 +// ##### `placeholder`
68 +//
69 +// Gets an [placeholder variable](/docs/conventions#placeholders).
70 +// The braces (`{}`) have to be omitted.
71 +//
72 +// ```
73 +// {{placeholder "http.request.uri.path"}}
74 +// {{placeholder "http.error.status_code"}}
75 +// ```
76 +//
77 // ##### `.Host`
78 //
79 // Returns the hostname portion (no port) of the Host header of the HTTP request.
modules/caddyhttp/templates/tplcontext.go
+8
@@ -29,6 +29,7 @@ import (
29
30 "github.com/Masterminds/sprig/v3"
31 "github.com/alecthomas/chroma/formatters/html"
32 + "github.com/caddyserver/caddy/v2"
33 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
34 "github.com/yuin/goldmark"
35 highlighting "github.com/yuin/goldmark-highlighting"
@@ -152,6 +153,7 @@ func (c templateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buff
153 "splitFrontMatter": c.funcSplitFrontMatter,
154 "listFiles": c.funcListFiles,
155 "env": c.funcEnv,
156 + "placeholder": c.placeholder,
157 })
158
159 parsedTpl, err := tpl.Parse(buf.String())
@@ -164,6 +166,12 @@ func (c templateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buff
166 return parsedTpl.Execute(buf, c)
167 }
168
169 +func (c templateContext) placeholder(name string) string {
170 + repl := c.Req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
171 + value, _ := repl.GetString(name)
172 + return value
173 +}
174 +
175 func (templateContext) funcEnv(varName string) string {
176 return os.Getenv(varName)
177 }