Skip to content

Commit f98f449

Browse files
authored
templates: Add pathEscape template function and use it in file browser (#6278)
* use url.PathEscape in file-server browse template - add `pathEscape` to c.tpl.Funcs, using `url.PathEscape` - use `pathEscape` in browse.html in place of `replace` * document `pathEscape` * Remove unnecessary pipe of img src to `html`
1 parent e66040a commit f98f449

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

modules/caddyhttp/fileserver/browse.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
</svg>
2222
{{- else if .HasExt ".jpg" ".jpeg" ".png" ".gif" ".webp" ".tiff" ".bmp" ".heif" ".heic" ".svg"}}
2323
{{- if eq .Tpl.Layout "grid"}}
24-
<img loading="lazy" src="{{.Name | replace "#" "%23" | replace "?" "%3f" | html}}">
24+
<img loading="lazy" src="{{.Name | pathEscape}}">
2525
{{- else}}
2626
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-photo" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
2727
<path stroke="none" d="M0 0h24v24H0z" fill="none"/>

modules/caddyhttp/templates/templates.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,18 @@ func init() {
300300
// find the documentation on time layouts [in Go's docs](https://pkg.go.dev/time#pkg-constants).
301301
// The default time layout is `RFC1123Z`, i.e. `Mon, 02 Jan 2006 15:04:05 -0700`.
302302
//
303+
// ##### `pathEscape`
304+
//
305+
// Passes a string through `url.PathEscape`, replacing characters that have
306+
// special meaning in URL path parameters (`?`, `&`, `%`).
307+
//
308+
// Useful e.g. to include filenames containing these characters in URL path
309+
// parameters, or use them as an `img` element's `src` attribute.
310+
//
311+
// ```
312+
// {{pathEscape "50%_valid_filename?.jpg"}}
313+
// ```
314+
//
303315
// ```
304316
// {{humanize "size" "2048000"}}
305317
// {{placeholder "http.response.header.Content-Length" | humanize "size"}}

modules/caddyhttp/templates/tplcontext.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"io/fs"
2222
"net"
2323
"net/http"
24+
"net/url"
2425
"os"
2526
"path"
2627
"reflect"
@@ -91,6 +92,7 @@ func (c *TemplateContext) NewTemplate(tplName string) *template.Template {
9192
"httpError": c.funcHTTPError,
9293
"humanize": c.funcHumanize,
9394
"maybe": c.funcMaybe,
95+
"pathEscape": url.PathEscape,
9496
})
9597
return c.tpl
9698
}

0 commit comments

Comments
 (0)