Skip to content

Commit

Permalink
templates: Implement placeholders function (#3324)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
bagbag and mholt authored Jul 20, 2020
1 parent 28d870c commit 2bc30bb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
10 changes: 10 additions & 0 deletions modules/caddyhttp/templates/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@ func init() {
// {{env "VAR_NAME"}}
// ```
//
// ##### `placeholder`
//
// Gets an [placeholder variable](/docs/conventions#placeholders).
// The braces (`{}`) have to be omitted.
//
// ```
// {{placeholder "http.request.uri.path"}}
// {{placeholder "http.error.status_code"}}
// ```
//
// ##### `.Host`
//
// Returns the hostname portion (no port) of the Host header of the HTTP request.
Expand Down
8 changes: 8 additions & 0 deletions modules/caddyhttp/templates/tplcontext.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (

"github.com/Masterminds/sprig/v3"
"github.com/alecthomas/chroma/formatters/html"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/yuin/goldmark"
highlighting "github.com/yuin/goldmark-highlighting"
Expand Down Expand Up @@ -152,6 +153,7 @@ func (c templateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buff
"splitFrontMatter": c.funcSplitFrontMatter,
"listFiles": c.funcListFiles,
"env": c.funcEnv,
"placeholder": c.placeholder,
})

parsedTpl, err := tpl.Parse(buf.String())
Expand All @@ -164,6 +166,12 @@ func (c templateContext) executeTemplateInBuffer(tplName string, buf *bytes.Buff
return parsedTpl.Execute(buf, c)
}

func (c templateContext) placeholder(name string) string {
repl := c.Req.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
value, _ := repl.GetString(name)
return value
}

func (templateContext) funcEnv(varName string) string {
return os.Getenv(varName)
}
Expand Down

0 comments on commit 2bc30bb

Please sign in to comment.